Advertisement
Sandhya_Singh

Linked List

Sep 2nd, 2014
221
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. class Node
  2. {
  3. int data;
  4. Node next;
  5. Node(int val) // Constructor to create a node
  6. {
  7. data=val;
  8. next=null;
  9. }
  10. void link(Node n)
  11. {
  12. next=n;
  13. }
  14. }
  15. class LinkList
  16. {
  17. Node head;
  18. LinkList(Node n)
  19. {
  20. head=n;
  21. }
  22. void print() //Method to print the value of list
  23. {
  24. Node nodePtr=head;
  25. System.out.print("[");
  26. while(nodePtr!=null)
  27. {
  28. System.out.print(nodePtr.data+" ");
  29. nodePtr=nodePtr.next;
  30. }
  31. System.out.println("]");
  32. }
  33. void putAtStart(int val) // Method to add a node at the start Position
  34. {
  35.  
  36. Node newNode=new Node(val);
  37. newNode.next=head;
  38. head=newNode;
  39.  
  40. }
  41. void putAtLast(int val1) //Method to add a node at the last position (Problem is here...)
  42. {
  43. Node nodePtr1=head;
  44. Node newNode1=new Node(val1);
  45. newNode1.next=null;
  46. while(nodePtr1!=null)
  47. {
  48. nodePtr1=nodePtr1.next;
  49. }
  50. nodePtr1.next=newNode1;
  51. }
  52. }
  53. public class LinkedList
  54. {
  55. public static void main(String args[])
  56. {
  57. Node n1=new Node(5);
  58. Node n2=new Node(12);
  59. Node n3=new Node(22);
  60. Node n4=new Node(6);
  61. n1.link(n2);
  62. n2.link(n3);
  63. n3.link(n4);
  64. LinkList list1=new LinkList(n1);
  65. list1.print();
  66. System.out.println("Adding some value at the start posision");
  67. list1.putAtStart(25);
  68. list1.putAtStart(99);
  69. list1.print();
  70. System.out.println("Adding some value at the last posision");
  71. list1.putAtLast(57);
  72. list1.putAtLast(64);
  73. list1.print();
  74. }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement