Presentation is loading. Please wait.

Presentation is loading. Please wait.

Linked List :: Basic Concepts

Similar presentations


Presentation on theme: "Linked List :: Basic Concepts"— Presentation transcript:

1 Linked List :: Basic Concepts
A list refers to a set of items organized sequentially. An array is an example of a list. The array index is used for accessing and manipulation of array elements. Problems with array: The array size has to be specified at the beginning. Deleting an element or inserting an element may require shifting of elements.

2 Linked List Structure Variable 1 item Structure Variable 2 item

3 Linked List Facts Each structure of the list is called a node, and consists of two fields: Item(s). Address of the next item in the list. The data items comprising a linked list need not be contiguous in memory. They are ordered by logical links that are stored as part of the data in the structure itself.

4 Declaration of a linked list
struct node { int item; struct node *next; } ; Such structures which contain a member field pointing to the same structure type are called self-referential structures. node item next

5 Illustration Consider the structure:
struct stud { int roll; char name[30]; int age; struct stud *next; }; Also assume that the list consists of three nodes n1, n2 and n3. struct stud n1, n2, n3;

6 Illustration To create the links between nodes, we can write:
n1.next = &n2 ; n2.next = &n3 ; n3.next = NULL ; /* No more nodes follow */ Now the list looks like: roll name age next n3 n2 n1

7 Example #include <stdio.h> struct stud { int roll;
char name[30]; int age; struct stud *next; }; main() struct stud n1, n2, n3; struct stud *p; scanf (“%d %s %d”, &n1.roll, n1.name, &n1.age); scanf (“%d %s %d”, &n2.roll, n2.name, &n2.age); scanf (“%d %s %d”, &n3.roll, n3.name, &n3.age); n1.next = &n2 ; n2.next = &n3 ; n3.next = NULL ; /* Now traverse the list and print the elements */ p = &n1 ; /* point to 1st element */ while (p != NULL) { printf (“\n %d %s %d”, p->roll, p->name, p->age); p = p->next; }

8 Linked List Where to start and where to stop? Head / Start End / Last
Structure Variable 1 item Structure Variable 2 item Structure Variable 3 item End / Last

9 Insert into a linked list
Head / Start item item item End / Last

10 Print items of a linked list
Head item item item item item item NULL

11 Example #include <stdio.h> struct stud { int roll;
char name[30]; int age; struct stud *next; }; main() struct stud n1, n2, n3, *p; …………….. p = &n1 ; /* point to 1st element */ while (p != NULL) printf (“\n %d %s %d”, p->roll, p->name, p->age); p = p->next; } ……………

12 Insert into a linked list
Step 1: Create a new node. Step 2: Copy the item. Step 3: Make the link/next as NULL (point nowhere) Step 4: Case 1: If there does not exists any linked list. Step 4a: Make the new node as head node. Step 4b: Go to End. Case 2: Else Step 4c: Locate the insertion point. Step 4d: Insert the new node. Step 4e: Adjust the link. Step 4f: Go to End.

13 Insert into a linked list
item NULL Step 1: Create a new node. Step 2: Copy the item. Step 3: Make the link/next as NULL (point nowhere) Step 4: Case 1: If there does not exists any linked list. Step 4a: Make the new node as head node. Step 4b: Go to End.

14 Insert into a linked list
item NULL item Head NULL Step 1: Create a new node. Step 2: Copy the item. Step 3: Make the link/next as NULL (point nowhere) Step 4: Case 2: Else Step 4c: Locate the insertion point. Step 4d: Insert the new node. Step 4e: Adjust the link. Step 4f: Go to End.

15 Insert into a linked list: Head Node
item NULL Head item NULL Step 4ci: Make the next of new node as the address of existing head node. Step 4cii: Copy the address of the new node as the head node.

16 Insert into a linked list: End Node
item NULL Head item item item NULL Step 4ci: Traverse till last/end node. Step 4cii: Make the next of last node as the address of new node.

17 Insert into a sorted linked list
Head prev curr prev curr prev 12 14 16 18 curr 19 22 32 NULL

18 Delete a specific node from linked list
Head prev 12 14 16 18 curr 19 22 32 NULL

19 Delete End Node from linked list
curr item NULL Head prev item item item

20 Delete Head Node from a linked list
item Head item NULL

21 Linked list and Dynamic Memory Allocation
Head item item item item item item NULL

22 Linked list and Dynamic Memory Allocation
We need not know how many nodes are there. 2. Dynamic memory allocation provides a flexibility on the length of a linked list. 3. Example, struct node { int data; struct node *next; }; struct node *head, *temp; temp=(struct node *)malloc(sizeof(struct node)); temp->next=NULL; temp->data=10; head=temp; free(temp);

23 The Work to Add the Node newnode = (node *) malloc(sizeof(node));
typedef struct stud { int roll; char name[25]; int age; struct stud *next; } node; node *head; Create the new node Fill in the data field Deal with the next field Point to nil (if inserting to end) Point to current (front or middle) newnode = (node *) malloc(sizeof(node)); newnode->data = new_data; newnode->next = current ; current = newnode;

24 Three Types of Insertion
front end Get to the end, then add node In middle Get to the node before which the new node is to be inserted.

25 Header file : list.h #include <stdio.h>
#include <stdlib.h> struct node { int data; struct node * next; }; typedef struct node ELEMENT; typedef ELEMENT * LINK;

26 Create_node function ELEMENT * create_node(int data) { ELEMENT * new;
new = (ELEMENT *) malloc (sizeof (ELEMENT)); new -> data = data; return (new); }

27 insert at front ELEMENT * insertfront (int data, ELEMENT * head) {
ELEMENT * new; new = create_node(data); new -> next = head; return new; // return pointer to first node }

28 Insert at end ELEMENT * insertend (int data, ELEMENT * ptr) {
ELEMENT * new, *head; new = create_node(data); head = ptr; if (ptr == NULL ) { new -> next = NULL; return new; } while (ptr->next != NULL) ptr = ptr -> next; ptr -> next = new; new -> next = NULL; return head;

29 Sorted insert function
ELEMENT * insert (int data, ELEMENT * ptr) { LINK new, prev, first; new = create_node(data); if (ptr == NULL || data < ptr -> value){ // insert as new first node new -> next = ptr; return new; // return pointer to first node }

30 else { // not first one first = ptr; // remember start prev = ptr; ptr = ptr -> next; // second while (ptr != NULL && data > ptr -> data) { ptr = ptr -> next; } prev -> next = new; // link in new -> next = ptr; //new node return first; } // end else } // end insert

31 Deletion To delete a data item from a linked list involves (assuming it occurs only once!): finding the data item in the list, and linking out this node, and freeing up this node as free space.

32 Example of Deletion first prev ptr 3 5 8 When ptr finds the item to be deleted, e.g. 8, we need the previous node to make the link to the next one after ptr (i.e. ptr -> next). Also check whether first node is to be deleted.

33 // delete the item from ascending list
ELEMENT * delete_item(int data, ELEMENT * ptr) { LINK prev, first; first = ptr; // remember start if (ptr == NULL) { return NULL; } else if (data == ptr -> data) // first node { ptr = ptr -> next; // second node free(first); // free up node return ptr; // second

34 else // check rest of list
{ prev = ptr; ptr = ptr -> next; // find node to delete while (ptr != NULL && data > ptr->data) ptr = ptr -> next; }

35 if (ptr == NULL || data != ptr->data)
// NOT found in ascending list // nothing to delete { return first; // original } else // found, delete ptr node prev -> next = ptr -> next; free(ptr); // free node } // end delete

36 Representation with Dummy Node
10 17 head dummy node Insertion at the beginning is the same as insertion after the dummy node

37 Initialization head typedef struct list { int data; struct list *next;
Write a function that initializes LIST typedef struct list { int data; struct list *next; } ELEMENT; ELEMENT* Initialize (int element) { ELEMENT *head; head = (ELEMENT *)malloc(sizeof(data)); // Create initial node head->data = element; head -> next = NULL; return head; }

38 Insert head head

39 printf("\nInvalid index %d\n", position); return head;
ELEMENT* Insert(ELEMENT *head, int element, int position) { int i=0; ELEMENT *temp, *new; if (position < 0) { printf("\nInvalid index %d\n", position); return head; } temp = head; for(i=0;i<position;i++){ temp=temp->next; if(temp==NULL) { new = (ELEMENT *)calloc(1,sizeof(ELEMENT)); new ->data = element; new -> next = temp -> next; temp -> next = new;

40 Delete head temp head temp

41 ELEMENT* Delete(data *head, int position) {
int i=0;data *temp,*hold; if (position < 0) { printf("\nInvalid index %d\n", position); return head; } temp = head; while ((i < position) && (temp -> next != NULL)) { temp = temp -> next; i++; if (temp -> next == NULL) { hold = temp -> next; temp -> next = temp -> next -> next; free(hold);

42 Linked list and Dynamic Memory Allocation
We need not know how many nodes are there. 2. Dynamic memory allocation provides a flexibility on the length of a linked list. 3. Example, struct node { int item; struct node *next; }; struct node *head, *temp; temp=(struct node *)malloc(sizeof(struct node)*1); temp->next=NULL; temp->item=10; head=temp; free(temp);

43 Array versus Linked Lists
Arrays are suitable for: Inserting/deleting an element at the end. Randomly accessing any element. Searching the list for a particular value. Linked lists are suitable for: Inserting an element. Deleting an element. Applications where sequential access is required. In situations where the number of elements cannot be predicted beforehand.

44 Types of Lists Depending on the way in which the links are used to maintain adjacency, several different types of linked lists are possible. Linear singly-linked list (or simply linear list) One we have discussed so far. A B C head

45 Circular linked list The pointer from the last element in the list points back to the first element. A B C head

46 Doubly linked list Pointers exist between adjacent nodes in both directions. The list can be traversed either forward or backward. Usually two pointers are maintained to keep track of the list, head and tail. A B C head end

47 Basic Operations on a List
Creating a list Traversing the list Inserting an item in the list Deleting an item from the list Concatenating two lists into one

48 List is an Abstract Data Type
A class of objects whose logical behavior is defined by a set of values and a set of operations. What is an abstract data type (ADT)? It is a data type defined by the user. It is defined by it’s behavior (semantics) Typically more complex than simple data types like int, float, etc. Why abstract? Because details of the implementation are hidden. When you do some operation on the list, say insert an element, you just call a function. Details of how the list is implemented or how the insert function is written is no longer required.

49 Example Write a C Program to store student course information using structures with Dynamically Memory Allocation. Input: Enter number of records: 2 Enter name of the subject and marks respectively: Programming 22 Structure 33 Output: Displaying Information: Programming Structure

50 struct course { char sname[MAXC] ; int marks; struct course * next; }

51 int main () { int num, i; struct course. head = NULL; struct course
int main () { int num, i; struct course * head = NULL; struct course * new, *p; printf (“number of courses?”) ; scanf (“%d”, &num) ; for (i=0; i<num; i++) { new = malloc (sizeof (struct course)) ; new->next = head; scanf (“%s”, new->sname) ; scanf(“%d”, &new->marks); head = new; } p =head; while (p!=NULL) { printf (“%s -- %d\n”, p->sname, p->marks) ; p=p->next;

52 int main () { int num, i; struct course. head = NULL; struct course
int main () { int num, i; struct course * head = NULL; struct course * new, *p; printf (“number of courses?”) ; scanf (“%d”, &num) ; for (i=0; i<num; i++) { new = malloc (sizeof (struct course)) ; if (head==NULL) head = new; else p->next = new; scanf (“%s”, new->sname) ; scanf(“%d”, &new->marks); p = new; } new->next = NULL; p =head; while (p!=NULL) { printf (“%s -- %d\n”, p->sname, p->marks) ; p=p->next;

53 Example Write a C program to create a 2 dimensional array initialized with zero using dynamic memory allocation. Input is number of rows and columns. Input : Number of rows: 3 Number of columns: 4 Output : Print the array.

54 Exercise Write a C program that will take a fixed integer as input and check whether the system you are using is Little Endian or Big Endian. Print “NA” if you find this information is not enough for the purpose.

55 Exercise Write a C program to print the number of words, lines and characters in a line text.


Download ppt "Linked List :: Basic Concepts"

Similar presentations


Ads by Google