java - Why I am not able to Pop Element from stack using Linked List Implementation? -
problem:
i not able pop element second time. example have 4,3,2,1 4 on top of stack.i not able delete 3,2
can guide me why?
below stack implementation :
public static void push(int data){ if(head==null){ node newnode=new node(data); head=newnode; }else{ node newnode1=new node(data); newnode1.next=head; head=newnode1; } } public static int pop(){ if(head==null){ return 0; } else{ node temp=head; int a=temp.data; temp=null; return a; } } public static void traverse(){ node temp=head; while(temp!=null){ system.out.println(temp.data); temp=temp.next; } }
you have problem in pop method
public static int pop(){ if(head==null){ return 0; } else{ node temp=head; head = head.next; int a=temp.data; temp=null; return a; } }
you forgot move head next node.
Comments
Post a Comment