Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Node
- {
- int data;
- Node next;
- Node(int val) // Constructor to create a node
- {
- data=val;
- next=null;
- }
- void link(Node n)
- {
- next=n;
- }
- }
- class LinkList
- {
- Node head;
- LinkList(Node n)
- {
- head=n;
- }
- void print() //Method to print the value of list
- {
- Node nodePtr=head;
- System.out.print("[");
- while(nodePtr!=null)
- {
- System.out.print(nodePtr.data+" ");
- nodePtr=nodePtr.next;
- }
- System.out.println("]");
- }
- void putAtStart(int val) // Method to add a node at the start Position
- {
- Node newNode=new Node(val);
- newNode.next=head;
- head=newNode;
- }
- void putAtLast(int val1) //Method to add a node at the last position (Problem is here...)
- {
- Node nodePtr1=head;
- Node newNode1=new Node(val1);
- newNode1.next=null;
- while(nodePtr1!=null)
- {
- nodePtr1=nodePtr1.next;
- }
- nodePtr1.next=newNode1;
- }
- }
- public class LinkedList
- {
- public static void main(String args[])
- {
- Node n1=new Node(5);
- Node n2=new Node(12);
- Node n3=new Node(22);
- Node n4=new Node(6);
- n1.link(n2);
- n2.link(n3);
- n3.link(n4);
- LinkList list1=new LinkList(n1);
- list1.print();
- System.out.println("Adding some value at the start posision");
- list1.putAtStart(25);
- list1.putAtStart(99);
- list1.print();
- System.out.println("Adding some value at the last posision");
- list1.putAtLast(57);
- list1.putAtLast(64);
- list1.print();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement