Linked List :: Basic Concepts

Slides:



Advertisements
Similar presentations
Pointers.
Advertisements

Linked Lists.
DATA STRUCTURES USING C++ Chapter 5
Singly Linked List BTECH, EE KAZIRANGA UNIVERSITY.
Linked List Variations
Data Structure Lecture-5
Data Structure Lecture-3 Prepared by: Shipra Shukla Assistant Professor Kaziranga University.
Review Learn about linked lists
Introduction to C Programming CE Lecture 20 Insertion and Deletion with Linear Linked Lists.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 17: Linked Lists.
C++ Programming: Program Design Including Data Structures, Fifth Edition Chapter 17: Linked Lists.
Data Structures Using C++ 2E
Implementation of Linked List For more notes and topics visit: eITnotes.com.
Data Structures Week 5 Further Data Structures The story so far  We understand the notion of an abstract data type.  Saw some fundamental operations.
Lists 1. Introduction Data: A finite sequence of data items. Operations: Construction: Create an empty list Empty: Check if list is empty Insert: Add.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 17: Linked Lists.
Lists Chapter 8. 2 Linked Lists As an ADT, a list is –finite sequence (possibly empty) of elements Operations commonly include: ConstructionAllocate &
APS105 Lists. Structures Arrays allow a collection of elements –All of the same type How to collect elements of different types? –Structures; in C: struct.
Data Structures. Abstract Data Type A collection of related data is known as an abstract data type (ADT) Data Structure = ADT + Collection of functions.
Chapter 17: Linked Lists. Objectives In this chapter, you will: – Learn about linked lists – Learn the basic properties of linked lists – Explore insertion.
Array 10 GB Hard Disk 2 GB 4 GB2 GB 3 GB DATA 4 GB Free Store data in the form of Array (Continuous memory locations) Solution-1: No Solution. Memory Insufficient.
1 Linked List. 2 List A list refers to a sequence of data items  Example: An array The array index is used for accessing and manipulation of array elements.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 17: Linked Lists.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 18: Linked Lists.
UNIT-II Topics to be covered Singly linked list Circular linked list
LINKED LISTS.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
1 Linked List. List vs Arrays Two built-in data structures that can be used to organize data, or to create other data structures: Lists Arrays.
Linked Lists Source: presentation based on notes written by R.Kay, A. Hill and C.Noble ● Lists in general ● Lists indexed using pointer arrays ● Singly.
C Structures and Memory Allocation
Chapter 16: Linked Lists.
Linked List ADT used to store information in a list
Lecture 6 of Computer Science II
C++ Programming:. Program Design Including
Data Structure By Amee Trivedi.
Dynamic Allocation Review Structure and list processing
Introduction to Linked Lists
Lectures linked lists Chapter 6 of textbook
Data Structure Interview Question and Answers
Review Deleting an Element from a Linked List Deletion involves:
Lists CS 3358.
UNIT-3 LINKED LIST.
Linked List Variations
Data Structures Interview / VIVA Questions and Answers
Linked Lists head One downside of arrays is that they have a fixed size. To solve this problem of fixed size, we’ll relax the constraint that the.
Introduction to Data Structures
Lists.
CSCI 3333 Data Structures Linked Lists.
Linked List Sudeshna Sarkar.
Programmazione I a.a. 2017/2018.
LINKED LISTS CSCD Linked Lists.
Prof. Neary Adapted from slides by Dr. Katherine Gibson
Introduction to Linked Lists
Lists.
LINKED LISTS.
Circular Buffers, Linked Lists
Linked List Lesson xx   In this presentation, we introduce you to the basic elements of a linked list.
Sequences 11/27/2018 1:37 AM Singly Linked Lists Singly Linked Lists.
Further Data Structures
Programming Linked Lists.
Linked Lists.
Linked List.
Chapter 16 Linked Structures
Programming and Data Structure
Data Structures & Algorithms
General List.
(1 - 2) Introduction to C Data Structures & Abstract Data Types
BY PROF. IRSHAD AHMAD LONE.
Arrays and Pointers.
CMPT 225 Lecture 5 – linked list.
Presentation transcript:

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.

Linked List Structure Variable 1 item Structure Variable 2 item

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.

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

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;

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

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; }

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

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

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

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; } ……………

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.

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.

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.

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.

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.

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

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

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

Delete Head Node from a linked list item Head item NULL

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

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);

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;

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.

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

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

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 }

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;

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 }

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

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.

Example of Deletion first prev ptr 3 5 8 12 - 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.

// 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

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

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

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

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; }

Insert head head

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;

Delete head temp head temp

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);

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);

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.

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

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

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

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

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.

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 22 Structure 33

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

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;

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;

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.

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.

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