Data Structures (CS301) Linked List and its implementation Virtual University of Pakistan
Objective Objective of this presentation is to teach you the concept and implementation of list data structure by using linked list Virtual University PAkistan
What is a linked list? It is a dynamic data structure. Linked list consist of series of nodes Chain the nodes together to form a linked list Structure of each node is like the one given below Data Next 1000 Virtual University PAkistan
Linked list Analogy to a train Insert a node with value ‘2’ in existing list
Graphical Representation of Linked List Picture of our list (2, 6, 8, 7, 1) stored as a linked list: 8000 1000 2 3000 6 5000 8 2000 7 6000 1 headNode lastcurrentNode currentNode Size = 5 Virtual University PAkistan
C++ Code for linked list We need two classes to implement linked list: Node Class List class In addition to linked list class and node class, we also need a function main() from where execution of our program will start. Virtual University PAkistan
Example Create a list of students using linked list data structure.
Defining a Node class (Student) class Student { char* Rollno; Student *NextStudent; public: Student() // Constructor Rollno=""; NextStudent=NULL; } void Set_RollNo(char* rno) //Setter function to set data member Rollno Rollno = rno; char* Get_RollNo() //Getter function to get value of Rollno return Rollno;
Node class (Student) Con’t void SetNextStudent(Student *NS) //Setter function to set NextStudent { NextStudent = NS; } Student* getNextStudent() //Getter function to get value of NextStudent return NextStudent; };
StudentList class class StudentList { private: Student *HeadStudent,*CurrentStudent; public: StudentList::StudentList() // Constructor HeadStudent = new Student(); HeadStudent->SetNextStudent(NULL); CurrentStudent = NULL; } HeadStudent 8000 8000 CurrentStudent NULL
Add function void Add_Student(char* rno) // Function to add students in list { Student *NewStudent = new Student(); NewStudent->Set_RollNo(rno); NewStudent->SetNextStudent(NULL); if(CurrentStudent == NULL) HeadStudent = NewStudent; CurrentStudent = NewStudent; } else CurrentStudent->SetNextStudent(NewStudent); CurrentStudent= NewStudent; cout<<CurrentStudent->Get_RollNo();
Main() function main() // Main() function { StudentList S; S.Add_Student("MC000000000."); cout<<endl; S.Add_Student("MC000000001."); S.Add_Student("MC000000002."); system("pause"); }
Output
Your Tasks Task 1: Remove the following line from end of Add() function. cout<<CurrentStudent->Get_RollNo(); Task 2: Add traverse (display) function to display roll number of students. Task3: Add more attributes (name, GPA, semester etc) in student class and make changes in your code accordingly.