110 likes | 234 Views
CSE 246 Data Structures and Algorithms. Spring2011 Lecture#5. More on Linked List. Analysis of Linked list Other operation on link list Delete(item) Update( item,value ) List length() inserFirst () insertLast () insertAfter ( listposition , value) InsertBefore ( listposition , value)
E N D
CSE 246Data Structures and Algorithms Spring2011 Lecture#5
More on Linked List Analysis of Linked list Other operation on link list • Delete(item) • Update(item,value) • List length() • inserFirst() • insertLast() • insertAfter(listposition, value) • InsertBefore(listposition, value) • Use of head and tail reference. Quratulain Rajput
Analysis of Linked list • Contiguous memory is not required. • Each node is linked through references to make a list. • No limit to store item in a list. • Space is required with each node to store reference of the next node. • Require start reference to indicate beginning of a list. • Last node contain null reference that indicate end of list. Quratulain Rajput
Implementation of Node class class Node{ int data; Node next; Node () { // no argument constructor data=0; next=null; } Node (int V) { // one argument constructor data=V; next=null; } } Quratulain Rajput
Implementation of List class class LIST{ Node Head; LIST (){ Head=null; } // list operations } Quratulain Rajput
Insert operation in linked list public void INSERT(int value){ Node NewNode=new Node(value); Node Temp=null, Prev=null; if(Head==null){ Head=NewNode; }else{ Temp=Head; while(Temp!=null){ Prev=Temp; Temp=Temp.next;} Prev.next=NewNode; } } Quratulain Rajput
Display list items public void DisplayList(){ Node Temp=Head; inti=0; while(Temp!=null){ i++; System.out.println("Item "+i+ Temp.data); Temp=Temp.next; } } Quratulain Rajput
getLength() method of List Public intgetLength() { Node Temp=Head; int counter=0; while(Temp!=null) { counter++; Temp=Temp.next; } return counter; } Quratulain Rajput
Delete item by position from list Public void DelNode(int position) { int counter=0; Node Temp=Head; while((counter!=position)&&(Temp!=null)) { counter++; Temp=Temp.next; } if(counter!=position) System.out.println(“Item does not exist”); else System.out.println(“Item has been deleted”); } Traverse a list until counter reach to given position than delete that node. Quratulain Rajput
Delete item by value Public void DelNode(int value) { Node Temp=Head; If (Head.data==value) Head=Head.next; else { while(Temp!=null &&(Temp.next.data != value)) { Temp=Temp.next; } Temp.next=Temp.next.next; } } • Two conditions possible • Value stored at first node • Change only Head • Value stored other than first node • -find node that contain value and then delete it. Quratulain Rajput
Update item of a list • Homework Public updateItem(int v, int x); Quratulain Rajput