Presentation is loading. Please wait.

Presentation is loading. Please wait.

Linked Lists A linked list is a series of connected nodes Each node contains at least –A piece of data (any type) –Pointer to the next node in the list.

Similar presentations


Presentation on theme: "Linked Lists A linked list is a series of connected nodes Each node contains at least –A piece of data (any type) –Pointer to the next node in the list."— Presentation transcript:

1 Linked Lists A linked list is a series of connected nodes Each node contains at least –A piece of data (any type) –Pointer to the next node in the list Head: pointer to the first node The last node points to NULL A P BC

2 Node A datapointer node

3 #include class linklist { private: struct node { int data; node *link; }*p; public: linklist(); void append( int num ); void add_as_first( int num ); void addafter( int c, int num ); void del( int num ); void display(); int count(); ~linklist(); }; A Simple Linked List Class

4 Constructor linklist::linklist() { p=NULL; }

5 Inserting a new node Possible cases: 1.Insert into an empty list 2.Insert as a first node in the list 3.Insert at back of the list (append) 4.Insert in middle of the list

6 Append Function void linklist::append(int num) { node *q,*t; if( p == NULL ) { p = new node; p->data = num; p->link = NULL; } else { q = p; while( q->link != NULL ) q = q->link; t = new node; t->data = num; t->link = NULL; q->link = t; }

7 Add_as_ first Function void linklist::add_as_first(int num) { node *q; q = new node; q->data = num; q->link = p; p = q; } newNode P 1 2

8 Addafter Function void linklist::addafter( int c, int num) { node *q,*t; int i; for(i=0,q=p;i<c;i++) { q = q->link; if( q == NULL ) { cout<<"\nThere are less than "<<c<<" elements."; return; } t = new node; t->data = num; t->link = q->link; q->link = t; } newNode 1 2

9 Del Function void linklist::del( int num ) { node *q,*r; q = p; if( q->data == num ) { p = q->link; delete q; return; } r = q; while( q!=NULL ) { if( q->data == num ) { r->link = q->link; delete q; return; } r = q; q = q->link; } cout<<"\nElement "<<num<<" not Found."; }

10 Display Function void linklist::display() { node *q; cout<<endl; for( q = p; q != NULL; q = q->link ) cout data; }

11 Count Function int linklist::count() { node *q; int c=0; for( q=p; q != NULL; q = q->link ) c++; return c; }

12 Destructor Function linklist::~linklist() { node *q; if( p == NULL ) return; while( p != NULL ) { q = p->link; delete p; p = q; }


Download ppt "Linked Lists A linked list is a series of connected nodes Each node contains at least –A piece of data (any type) –Pointer to the next node in the list."

Similar presentations


Ads by Google