lecture 5 linked list updated

83
Data Structures & Algorithms Dated: 30-12-2010

Upload: ahmed-ijaz

Post on 04-Apr-2015

85 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Lecture 5 Linked List Updated

Data Structures & Algorithms

Dated: 30-12-2010

Page 2: Lecture 5 Linked List Updated

Review Pointers

Linked List

Representation of Linked List

Operations of Linked List

Circular Linked List

Today Topics

Page 3: Lecture 5 Linked List Updated

What is Linked List?Linked List can be defined as:

It is a very common data structure often used to store similar data in memory.

Linked list is a collection of elements called nodes, each of which stores two items of information.

An element of the list and a link

Link is a pointer or an address that indicates explicitly the location of the node containing the successor of the list element.

Page 4: Lecture 5 Linked List Updated

What is Linked List? While the elements of an array occupy

contiguous memory location, those of a linked list are not constrained to be stored in adjacent locations.

The individual elements are stored “somewhere” in memory.

There are two types of linked list Single-linked list or One-Way lists Double-linked list or Two-Way lists

Page 5: Lecture 5 Linked List Updated

The LIST Data Structure

The List is among the most generic of data structures.

Real life:

a. shopping list, b. groceries list, c. list of people to invite to dinnerd. List of presents to get

Page 6: Lecture 5 Linked List Updated

6

Lists

A list is collection of items that are all of the same type (grocery items, integers, names)

The items, or elements of the list, are stored in some particular order

It is possible to insert new elements into various positions in the list and remove any element of the list

Page 7: Lecture 5 Linked List Updated

AL 7

Lists

List is a set of elements in a linear order. For example, data values a1, a2, a3, a4 can be arranged in a list:

(a3, a1, a2, a4)

In this list, a3, is the first element, a1 is the second element, and so on

The order is important here; this is not just a random collection of elements, it is an ordered collection

Page 8: Lecture 5 Linked List Updated

8

List Operations

Useful operations createList(): create a new list (presumably empty) copy(): set one list to be a copy of another clear(); clear a list (remove all elments) insert(X, ?): Insert element X at a particular position

in the list remove(?): Remove element at some position in

the list get(?): Get element at a given position update(X, ?): replace the element at a given position

with X find(X): determine if the element X is in the list length(): return the length of the list.

Page 9: Lecture 5 Linked List Updated

AL 9

List Operations

We need to decide what is meant by “particular position”; we have used “?” for this.

There are two possibilities:

1. Use the actual index of element: insert after element 3, get element number 6. This approach is taken by arrays

2. Use a “current” marker or pointer to refer to a particular position in the list.

Page 10: Lecture 5 Linked List Updated

AL 10

List Operations

If we use the “current” marker, the following four methods would be useful:

start(): moves to “current” pointer to the very first element.

tail(): moves to “current” pointer to the very last element.

next(): move the current position forward one element

back(): move the current position backward one element

Page 11: Lecture 5 Linked List Updated

Character tics of linked list

Page 12: Lecture 5 Linked List Updated

Character tics of linked list

Page 13: Lecture 5 Linked List Updated

Example of Linked ListSpouse the marks obtained by different students can be stored in a linked list:

Data Link

Node

14 100 30 400 25 500 14 Null

200 100 400 500

The data part of each node consists of the marks obtained by a student.

The link part is a pointer to the next node.

The Null in the last node indicates that is the last node .

Page 14: Lecture 5 Linked List Updated

Representation of Linked List? The storage technique of linked list is different from

arrays

Items in linked list are stored in memory in scattered form but these are linked together through pointers

Each item of list is called an object

One object may contain one or more fields

Each object contains at least two fields

One field is used to store data and the other to store address of memory location of the next object

Page 15: Lecture 5 Linked List Updated

Some programming conceptUntil now, in all our programs, we have only had as much memory available as we declared for our variables, having the size of all of them to be determined in the source code, before the execution of the program. But, what if we need a variable amount of memory that can only be determined during runtime?

Operators new and new[]In order to request dynamic memory we use the operator new. new is followed by a data type specifier and -if a sequence of more than one element is required- the number of these within brackets []. It returns a pointer to the beginning of the new block of memory allocated. Its form is:

Page 16: Lecture 5 Linked List Updated

Some programming concept con…

pointer = new type pointer = new type [number_of_elements] The first expression is used to allocate memory to contain one single element of type type. The second one is used to assign a block (an array) of elements of type type, where number_of_elements is an integer value representing the amount of these. For example:

int * st; st = new int [5];

The first element pointed by st can be accessed either with the expression st[0] or the expression *st. Both are equivalent as has been explained in the section about pointers. The second element can be accessed either with st[1] or *(st+1) and so on...

Page 17: Lecture 5 Linked List Updated

Example of Linked List

The following example explains this concept using a C++ structure:

struct test{

int data;test *link;

};

test *start; “data” is of int type and is used to store integer values

in the node.

“link” as a pointer to store memory address for next node in the chain.

“Start” points to the structure type objects “test” . It is used to store the memory address of the first or starting object in memory

Page 18: Lecture 5 Linked List Updated

Example of Linked List In C++, nodes of the linked list are created by using

the “new” operator during the program execution.

The “new” operator allocates memory for the specified object and return its memory address to the pointer variable.

Its syntax is:pointer-variable = new object-

name;

The operator “->” (hyphen and greater than sign) is used to access the data of pointer type objects

Page 19: Lecture 5 Linked List Updated

Example of Linked List To allocate memory to variable “start” of “test” type

and store values in it. The statements are written as:

start = new test;start -> data = 10;start -> link = Null;

Suppose the memory address of variable “start” is 200. The storage in the memory will be:

10 Null200Start

Data Link

Page 20: Lecture 5 Linked List Updated

Creating Linked Lists in C++

A linked list is a data structure which is built from structures and pointers. It forms a chain of "nodes" with pointers representing the links of the chain and holding the entire thing together. A linked list can be represented by a diagram like this one:

Name: FredAge: 34Height: 1.7

Name: SueAge: 27Height: 1.2

Name: JoeAge: 48Height: 1.4

Name: ZoeAge: 30Height: 1.3

Start

Null

Page 21: Lecture 5 Linked List Updated

Defining the data structure for a linked list

The key part of a linked list is a structure, which holds the data for each node (the name, address, age or whatever for the items in the list), and, most importantly, a pointer to the next node. Here I have given the structure of a typical node:

struct node { char name[20]; // Name of up to 20 letters int age; // D.O.B. would be better float height; // In meters node *nxt; // Pointer to next node }; node *start

Page 22: Lecture 5 Linked List Updated

Adding a node to the end of the list

The first problem that we face is how to add a node to the list. For simplicity's sake, we will assume that it has to be added to the end of the list, although it could be added anywhere in the list (a problem I will deal with later on). Firstly, we declare the space for a pointer item and assign a temporary pointer to it. This is done using the new statement as follows:

temp = new node;

undefined

temp

Page 23: Lecture 5 Linked List Updated

Adding a node to the end of the list

Having declared the node, we ask the user to fill in the details of the person, i.e. the name, age, address or whatever:

cout << "Please enter the name of the person: "; cin >> temp->name; cout << "Please enter the age of the person : "; cin >> temp->age; cout << "Please enter the height of the person : "; cin >> temp->height; temp->nxt = NULL;

Page 24: Lecture 5 Linked List Updated

Adding a node to the end of the list

The last line sets the pointer from this node to the next to NULL, indicating that this node, when it is inserted in the list, will be the last node. Having set up the information, we have to decide what to do with the pointers. Of course, if the list is empty to start with, there's no problem - just set the Start pointer to point to this no

if (start == NULL) start = temp;

It is harder if there are already nodes in the list. In this case, the secret is to declare a second pointer, temp2, to step through the list until it finds the last node.

Page 25: Lecture 5 Linked List Updated

Adding a node to the end of the list

Start

temp2 = start_ptr; // We know this is not NULL - list not empty! while (temp2->nxt != NULL) { temp2 = temp2->nxt; // Move to next link in chain } temp2 = start_ptr; // We know this is not NULL - list not empty! while (temp2->nxt != NULL) { temp2 = temp2->nxt; // Move to next link in chain } temp2 = start_ptr; // We know this is not NULL - list not empty! while (temp2->nxt != NULL) { temp2 = temp2->nxt; // Move to next link in chain } temp2 = start_ptr; // We know this is not NULL - list not empty! while (temp2->nxt != NULL) { temp2 = temp2->nxt; // Move to next link in chain } temp2 = start_ptr; // We know this is not NULL - list not empty! while (temp2->nxt != NULL) { temp2 = temp2->nxt; // Move to next link in chain } temp2 = start_ptr; // We know this is not NULL - list not empty! while (temp2->nxt != NULL) { temp2 = temp2->nxt; // Move to next link in chain }

temp2 = start; // We know this is not NULL - list not empty! while (temp2->nxt != NULL) { temp2 = temp2->nxt; // Move to next link in chain }

Page 26: Lecture 5 Linked List Updated

Adding a node to the end of the list

The loop will terminate when temp2 points to the last node in the chain, and it knows when this happened because the nxt pointer in that node will point to NULL. When it has found it, it sets the pointer from that last node to point to the node we have just declared:

temp2->nxt = temp;

Name: FredAge: 34Height:1.7

Name: SueAge: 27Height:1.2

Name: JoeAge: 48Height:1.4

Name: ZoeAge: 30Height:1.3

Start

Null

Name: JoeAge: 48Height:1.4

temp2 temp

Page 27: Lecture 5 Linked List Updated

Adding a node to the end of the list

The link temp2->nxt in this diagram is the link joining the last two nodes. The full code for adding a node at the end of the list is shown below, in its own little function:

Page 28: Lecture 5 Linked List Updated

Adding a node to the end of the list void add_node_at_end () { node *temp, *temp2; // Temporary pointers // Reserve space for new node and fill it with

data temp = new node; cout << "Please enter the name of the person: "; cin >> temp->name; cout << "Please enter the age of the person : "; cin >> temp->age; cout << "Please enter the height of the person : "; cin >> temp->height; temp->nxt = NULL; // Set up link to this node if (start== NULL) start= temp; else { temp2 = start; // We know this is not NULL - list not empty! while (temp2->nxt != NULL) { temp2 = temp2->nxt; // Move to next link in chain } temp2->nxt = temp; }}

Page 29: Lecture 5 Linked List Updated

Displaying the list of nodes

Having added one or more nodes, we need to display the list of nodes on the screen. This is comparatively easy to do. Here is the method: Set a temporary pointer to point to the same thing as the start

pointer. If the pointer points to NULL, display the message "End of list"

and stop. Otherwise, display the details of the node pointed to by the

start pointer. Make the temporary pointer point to the same thing as the nxt

pointer of the node it is currently indicating. Jump back to step 2.

Page 30: Lecture 5 Linked List Updated

Displaying the list of nodes

temp = start_ptr; do { if (temp == NULL) cout << "End of list" << endl; else { // Display details for what temp points to cout << "Name : " << temp->name << endl; cout << "Age : " << temp->age << endl; cout << "Height : " << temp->height << endl; cout <<

endl; // Blank line // Move to next node (if present) temp = temp->nxt; } } while (temp != NULL);

Page 31: Lecture 5 Linked List Updated

Deleting a node from the list

When it comes to deleting nodes, we have three choices: Delete a node from the start of the list, delete one from the end of the list, or delete one from somewhere in the middle.

When a node is deleted, the space that it took up should be reclaimed. Otherwise the computer will eventually run out of memory space. This is done with the delete instruction:

delete tem However, we can't just delete the nodes willy-nilly as it would

break the chain. We need to reassign the pointers and then delete the node at the last moment. Here is how we go about deleting the first node in the linked list:

temp = start; // Make the temporary pointer // identical to the start pointer p; // Release the memory pointed to by temp

Page 32: Lecture 5 Linked List Updated

Deleting a node from the list

.

Name: FredAge: 34Height:1.7

Name: SueAge: 27Height:1.2

Name: ZoeAge: 30Height:1.3

Start

Etc.

temp

Page 33: Lecture 5 Linked List Updated

Deleting a node from the list

Now that the first node has been safely tagged (so that we can refer to it even when the start pointer has been reassigned), we can move the start pointer to the next node in the chain:

start= start->nxt; // Second node in chain. .

Name: FredAge: 34Height:1.7

Name: SueAge: 27Height:1.2

Name: ZoeAge: 30Height:1.3

Start

Etc.

temp

Page 34: Lecture 5 Linked List Updated

Deleting a node from the list

Name: FredAge: 34Height:1.7

Name: SueAge: 27Height:1.2

Start

Etc.

Here is the function that deletes a node from the start:

void delete_start_node() { node *temp; temp = start; start = start->nxt; delete temp; }

Page 35: Lecture 5 Linked List Updated

Deleting a node from the list

Deleting a node from the end of the list is harder, as the temporary pointer must find where the end of the list is by hopping along from the start.

This is done using code that is almost identical to that used to insert a node at the end of the list.

It is necessary to maintain two temporary pointers, temp1 and temp2.

The pointer temp1 will point to the last node in the list and temp2 will point to the previous node.

We have to keep track of both as it is necessary to delete the last node and immediately afterwards, to set the nxt pointer of the previous node to NULL (it is now the new last node).

Page 36: Lecture 5 Linked List Updated

Deleting a node from the list

1. Look at the start pointer. If it is NULL, then the list is empty, so print out a "No nodes to delete" message.

2. Make temp1 point to whatever the start pointer is pointing to. 3. If the nxt pointer of what temp1 indicates is NULL, then we've

found the last node of the list, so jump to step 7.4. Make another pointer, temp2, point to the current node in the list. 5. Make temp1 point to the next item in the list.6. Go to step 3.7. If you get this far, then the temporary pointer, temp1, should point

to the last item in the list and the other temporary pointer, temp2, should point to the last-but-one item.

8. Delete the node pointed to by temp1. 9. Mark the nxt pointer of the node pointed to by temp2 as NULL - it

is the new last node.

Page 37: Lecture 5 Linked List Updated

Deleting a node from the list

Let's try it with a rough drawing. This is always a good idea when you are trying to understand an abstract data type. Suppose we want to delete the last node from this list:

Name: FredAge: 34Height: 1.7

Name: SueAge: 27Height: 1.2

Name: JoeAge: 48Height: 1.4

Name: ZoeAge: 30Height: 1.3

Start

Null

Page 38: Lecture 5 Linked List Updated

Deleting a node from the list

Firstly, the start pointer doesn't point to NULL, so we don't have to display a "Empty list!" message. Let's get straight on with step2 - set the pointer temp1 to the same as the start pointer:

Name: FredAge: 34Height: 1.7

Name: SueAge: 27Height: 1.2

Name: JoeAge: 48Height: 1.4

Null

Name: ZoeAge: 30Height: 1.3

Start

temp1

Page 39: Lecture 5 Linked List Updated

Deleting a node from the list

The nxt pointer from this node isn't NULL, so we haven't found the end node. Instead, we set the pointer temp2 to the same node as temp1

Name: FredAge: 34Height: 1.7

Name: SueAge: 27Height: 1.2

Name: JoeAge: 48Height: 1.4

Null

Name: ZoeAge: 30Height: 1.3

Start

temp1

temp2

Page 40: Lecture 5 Linked List Updated

Deleting a node from the list

and then move temp1 to the next node in the list:

Name: FredAge: 34Height: 1.7

Name: SueAge: 27Height: 1.2

Name: JoeAge: 48Height: 1.4

Null

Name: ZoeAge: 30Height: 1.3

Start

Temp 2 temp1

Page 41: Lecture 5 Linked List Updated

Deleting a node from the list

Going back to step 3, we see that temp1 still doesn't point to the last node in the list, so we make temp2 point to what temp1 points to

Name: FredAge: 34Height: 1.7

Name: SueAge: 27Height: 1.2

Name: JoeAge: 48Height: 1.4

Null

Name: ZoeAge: 30Height: 1.3

Start

Temp2 Temp2

Page 42: Lecture 5 Linked List Updated

Deleting a node from the list

and temp1 is made to point to the next node along:

Name: FredAge: 34Height: 1.7

Name: SueAge: 27Height: 1.2

Name: JoeAge: 48Height: 1.4

Null

Name: ZoeAge: 30Height: 1.3

Start

Temp 2 Temp1

Page 43: Lecture 5 Linked List Updated

Deleting a node from the list

Eventually, this goes on until temp1 really is pointing to the last node in the list, with temp2 pointing to the penultimate node:

Name: FredAge: 34Height: 1.7

Name: SueAge: 27Height: 1.2

Name: JoeAge: 48Height: 1.4

Null

Name: ZoeAge: 30Height: 1.3

Start

Temp 1 Temp 2

Page 44: Lecture 5 Linked List Updated

Deleting a node from the list

Name: FredAge: 34Height: 1.7

Name: SueAge: 27Height: 1.2

Null

Name: ZoeAge: 30Height: 1.3

Start

Temp 2 Temp

Page 45: Lecture 5 Linked List Updated

Deleting a node from the list

Name: FredAge: 34Height: 1.7

Name: SueAge: 27Height: 1.2

Null

Name: ZoeAge: 30Height: 1.3

Start

Temp 2

and set the nxt pointer of what temp2 indicates to NULL:

Page 46: Lecture 5 Linked List Updated

Deleting a node from the list

I suppose you want some code for all that! All right then .... void delete_end_node() { node *temp1, *temp2; if (start == NULL) cout << "The list is empty!" << endl; else { temp1 = start; while (temp1->nxt != NULL) { temp2 = temp1; temp1 = temp1->nxt; } delete temp1; temp2->nxt = NULL; } }

Page 47: Lecture 5 Linked List Updated

Deleting a node from the list

The code seems a lot shorter than the explanation!

Now, the sharp-witted amongst you will have spotted a problem. If the list only contains one node, the code above will malfunction. This is because the function goes as far as the temp1 = start statement, but never gets as far as setting up temp2. The code above has to be adapted so that if the first node is also the last (has a NULL nxt pointer), then it is deleted and the startpointer is assigned to NULL. In this case, there is no need for the pointer temp2:

Page 48: Lecture 5 Linked List Updated

Deleting a node from the list

void delete_end_node() { node *temp1, *temp2; if (start_ptr == NULL) cout << "The list is empty!" << endl; else { temp1 = start_ptr; if (temp1->nxt == NULL) // This part is new! { delete temp1; start_ptr = NULL; } else { while (temp1->nxt != NULL) { temp2 = temp1; temp1 = temp1->nxt; } delete temp1; temp2->nxt = NULL; } } }

Page 49: Lecture 5 Linked List Updated

Navigating through the list

One thing you may need to do is to navigate through the list, with a pointer that moves backwards and forwards through the list, like an index pointer in an array.

This is certainly necessary when you want to insert or delete a node from somewhere inside the list, as you will need to specify the position.

I will call the mobile pointer current. First of all, it is declared, and set to the same value as the start pointer:

node *current; current = start;

Page 50: Lecture 5 Linked List Updated

Navigating through the list

Notice that you don't need to set current equal to the address of the start pointer, as they are both pointers. The statement above makes them both point to the same thing:

Name: FredAge: 34Height: 1.7

Name: SueAge: 27Height: 1.2

Etc.

Name: ZoeAge: 30Height: 1.3

Start current

Page 51: Lecture 5 Linked List Updated

Navigating through the list

It's easy to get the current pointer to point to the next node in the list (i.e. move from left to right along the list). If you want to move current along one node, use the nxt field of the node that it is pointing to at the moment:

current = current->nxt; In fact, we had better check that it isn't pointing to the

last item in the list. If it is, then there is no next node to move to:

if (current->nxt == NULL) cout << "You are at the end of the list." << endl; else current = current->nxt;

Page 52: Lecture 5 Linked List Updated

Navigating through the list

Moving the current pointer back one step is a little harder. This is because we have no way of moving back a step automatically from the current node. The only way to find the node before the current one is to start at the beginning, work our way through and stop when we find the node before the one we are considering the moment. We can tell when this happens, as the nxt pointer from that node will point to exactly the same place in memory as the current pointer (i.e. the current node).

Page 53: Lecture 5 Linked List Updated

if (current == start_ptr) cout << "You are at the start of the list" << endl;

else { node *previous; // Declare the pointer previous = start; while (previous->nxt != current) { previous = previous->nxt; } current = previous; }

Page 54: Lecture 5 Linked List Updated

Creating Linked List1. Define structure of node

2. Declare three pointer objects start, current & next of the type node

3. Create first node and assign its address to “start”. Also assign value to the node

start = new-nodenode = value

4. Assign address of start node to the current node to proceed next

current = start

Page 55: Lecture 5 Linked List Updated

Creating Linked List5. Repeat step-6 to 7 FOR C = 1 to 9

6. Create new node i.e. “next”

7. Assign value of new node “next” and address of new node “next” to current

new-node-data = valuecurrent = new-node

[end of step 2 loop]8. Exit

Page 56: Lecture 5 Linked List Updated

Example of Linked ListStart Current Next

10

200

200 200

20 Null

250

250

250

Page 57: Lecture 5 Linked List Updated

Operations on Linked List

Traversal: Processing each element in the array

Search: Finding the location of an element with a given value

Insertion: Adding a new element to an array

Deletion: Removing an element from an array

Sorting: Organizing the elements in some order

Page 58: Lecture 5 Linked List Updated

Algorithms of Traverse Operation

Traverse a linked List( LIST, PTR, INFO, DATA, NULL) let LIST be a linked list in memory. This algorithm traverses LIST , applying an operation PRINT to each element of LIST. The variable PTR points to the node currently being processed.

1. [initialize pointer PTR]. Set PTR:= START

2. Repeat step-3 to 4 While PRR != Null

3. Apply process PRINT to DATA[PTR]

4. Set PTR:=LINK[PTR]. [PTR now points to the next node.]

[end of step 2 loop]

5. Exit

Page 59: Lecture 5 Linked List Updated

Algorithms of Insert OperationInsertItem (X)

Algorithm to add new node at end of linked list1. Start2. Create a LIST3. Create a new node “Next”4. Assign value of X to new node “Next” and Null to address of

new node “Next”Next -> data = XNext -> link = Null

4. Assign the address of new node “Next” to current link and then to currentCurrent -> link = NextCurrent = Next

5. Exit

Page 60: Lecture 5 Linked List Updated

Algorithms of Insert OperationInsertItem (X)

Algorithm to add new node at beginning of linked list1. Start2. Create a LIST3. Create a new node “Next”4. Assign value of X to new node “Next” and Start value

to address of new node “Next”Next -> data = XNext -> link = Start

4. Assign the address of new node “Next” to StartStart = Next

5. Exit

Page 61: Lecture 5 Linked List Updated

Algorithms of Insert OperationInsertItem (X, Pos)

Algorithm to add new node at specified location of linked list1. Start2. Create a new node “Next”3. Assign value of X to new node “Next” and Null to address of new

node “Next”Next -> data = XNext -> link = Null

4. Repeat step-5 For C = 1 to Pos – 15. Curent-> link=next;6. next->link=pos + 1;7. Exit

Page 62: Lecture 5 Linked List Updated

Algorithms of Delete OperationDeleteItem ()

Algorithm to delete node at end of linked list1. Start2. temp = Current = Start3. Repeat step-4 to 5 While temp -> link != Null4. temp = temp -> link5. if temp -> link != Null then

Current = tempEnd if

6. Current -> link = Null7. Exit

Page 63: Lecture 5 Linked List Updated

Algorithms of Delete Operation

DeleteItem ()Algorithm to delete node at beginning of linked list

1. Start2. Start = Start -> link3. Exit

Page 64: Lecture 5 Linked List Updated

Algorithms of Delete OperationDeleteItem (Pos)

Algorithm to delete node at specified location of linked list1. Start2. temp = Next = Start3. temp = temp -> link4. Repeat step-5 For C = 1 to Pos – 15. if temp = Null then

Print “Invalid Position”Return

elseNext = temptemp = temp -> link

end if6. Next -> link = temp -> link7. Exit

Page 65: Lecture 5 Linked List Updated

Algorithm of Search OperationSearch (X)

Algorithm to search position of the given element in the linked list

1. Start2. temp = Start3. Pos = 14. Repeat step-5 to 7 While temp != Null5. if temp -> data = X then

Print PosReturn

End if6. temp = temp -> link7. Pos = Pos + 18. Exit

Page 66: Lecture 5 Linked List Updated

Circular Linked List A linked list in which the last node of the list

points back to the first node of the list is called circular linked list.

Difficult to detect the end of a circular linked list

To overcome this problem, the end of list is detected with reference to the pointer field of the nodes. If the pointer field value of any node in the list is equal to the starting address of the field, that node is the last node.

Page 67: Lecture 5 Linked List Updated

Example of Circular Linked List

A Circular Linked List having four nodes is given below:

14 100 30 400 25 500 14 200

200 100 400 500

Page 68: Lecture 5 Linked List Updated

Double Linked List A linear list in which each node has the

addresses both of the next node and of the previous node

Can be visited in both directions Forward direction Backward direction

Also called two-way list

Page 69: Lecture 5 Linked List Updated

Double Linked List The node consist of at least three field:

First field to store the information Second field to store address of the next

node Third field to store address of the previous

node

Previous Node Link

InformationNext Node

Link

Node

Page 70: Lecture 5 Linked List Updated

Example of Linked ListSpouse the marks obtained by different students can be stored in a linked list:

Null 14 100 200 30 400 100 14 Null

200 100 400

The data part of each node consists of the marks obtained by the student.

The next node link part is a pointer to the next node.

The previous node link part is a pointer to the previous node

The Null in the last node indicates that is the last node.

The Null in the first node indicates that is the first node.

Page 71: Lecture 5 Linked List Updated

Single Linked List vs Double Linked List

Major difference between single linked list and double linked list is:

Single linked list can be visited in one direction only (forward direction) whereas double linked list can be visited in two directions (forward and backward)

A previous node cannot be accessed from the current node in single linked list, whereas can be accessed in double linked list.

Page 72: Lecture 5 Linked List Updated

Double Linked List The following example explains this concept using a C++ structure

struct test{

test *previous;int data;test *next;

};

test *start; “previous” as a pointer to store memory address for previous

node in the linked list. “data” is of int type and is used to store integer values in the

node. “next” as a pointer to store memory address for next node in the

linked list.

Page 73: Lecture 5 Linked List Updated

Example of Double Linked List To allocate memory to variable “start” of “test” type

and store values in it. The statements are written as:start = new test;start -> previous = Null;start -> data = 10;start -> next = Null;

Suppose the memory address of variable “start” is 200. The storage in the memory will be:

Null 10 Null200Start

Pre. Data Next

Page 74: Lecture 5 Linked List Updated

Creating Double Linked List1. Define structure of node

2. Declare three pointer objects start, current & next of the type node

3. Create first node and assign its address to “start”. Also assign value to the node

start = new-nodenode = value

4. Assign address of start node to the current node to proceed next

current = start

Page 75: Lecture 5 Linked List Updated

Creating Double Linked List5. Repeat step-6 to 7 FOR C = 1 to 9

6. Create new node i.e. “next”

7. Assign value of new node “next” and address of new node “next” to current

new-node-data = valuecurrent = new-node

8. Exit

Page 76: Lecture 5 Linked List Updated

Creating Double Linked List The nodes for a doubly linked list would be defined as

follows: struct node { string name; node *nxt; // Pointer to next node node *prv; // Pointer to previous node }; node *current;

current = new node; current->name = "Fred"; current->nxt = NULL; current->prv = NULL;

Page 77: Lecture 5 Linked List Updated

Adding at the start and end void add_node_at_start (string new_name) { // Declare a temporary pointer and move it to the start node *temp = current; while (temp->prv != NULL) temp = temp->prv; // Declare a new

node and link it in

node *temp2; temp2 = new node; temp2->name = new_name; // Store the new name in the node temp2->prv = NULL; // This is the new start of the list temp2->nxt = temp; // Links to current list temp->prv = temp2; }

Page 78: Lecture 5 Linked List Updated

Adding at the start and end void add_node_at_end () { // Declare a temporary pointer and move it to the end node *temp = current; while (temp->nxt != NULL) temp = temp->nxt; // Declare a new

node and link it in

node *temp2; temp2 = new node; temp2->name = new_name; // Store the new name in the node temp2->nxt = NULL; // This is the new start of the list temp2->prv = temp; // Links to current list temp->nxt = temp2; }

Page 79: Lecture 5 Linked List Updated

Assignment # 3 (roll no#, name, marks)

Enter your option

1. Initialize the node (initialization can be done only once)

2. Insert before a specified node (you can not insert before initialization)

3. Insert after a specified node

4. Delete a particular node

5. Search the nodes

6. Display all the nodes

Page 80: Lecture 5 Linked List Updated

Enter your option

1. Initialize the node

2. Insert before a specified node

3. Insert after a specified node

4. Delete a particular node

5. Search the nodes

6. Display all the nodes 1

Enter Roll number 12

Enter the name Zafar

Enter the marks 200

Do you wish to continue[y/n]

Page 81: Lecture 5 Linked List Updated

Do you wish to continue[y/n]yEnter your option

1. Initialize the node

2. Insert before a specified node

3. Insert after a specified node

4. Delete a particular node

5. Search the nodes

6. Display all the nodes

Page 82: Lecture 5 Linked List Updated

1

Initialisation can occur only once.

Now you can insert a node

Enter your option

1. Initialize the node

2. Insert before a specified node

3. Insert after a specified node

4. Delete a particular node

5. Search the nodes

6. Display all the nodes

Page 83: Lecture 5 Linked List Updated

If you don’t initialize Enter your option

1. Initialize the node

2. Insert before a specified node

3. Insert after a specified node

4. Delete a particular node

5. Search the nodes

6. Display all the nodes 6

No. You must first initialize at least one node

Enter your option

1. Initialize the node

2. Insert before a specified node

3. Insert after a specified node

4. Delete a particular node

5. Search the nodes

6. Display all the nodes