Lecture#7
Lecture#7
implementation of a node
struct node
{
5 0x80010
int data;
node *next;
};
Creation of Linked List
class linked_list
{
private:
node *start; node * last;
public:
linked_list()
{ start=NULL; last= NULL;}
if (start == NULL)
{ 12 NULL
start=temp;
last=temp;
} last
start
else{ temp
temp->next=start;
12 NULL 15
start=temp; }
}
insert a node in between a linked
list
The steps for inserting a node between two nodes a and b:
1. Make a new node
node *tmp=new node
2. Point the ‘next’ of the new node to the node ‘b’ (the node
after which we have to insert the new node). Till now, two
nodes are pointing the same node ‘b’, the node ‘a’ and the
new node.
temp->next=b
while(temp!=NULL)
{
cout<<temp->data<<"\t";
temp=temp->next;
}
}
Delete last element in linked list
Check if the list isempty
if(start==NULL)
If it not empty check if it has one element only
if (start->next==NULL)
If it has more than onelement
Delete first element in linked list
Copy the address of first node i.e. start node to some temp
variable say temp start
node *temp= start; 10 20 30 NULL
temp
Move the start to the second node of the linked list i.e.
start
start=start->next;
10 20 30 NULL
temp
Disconnect the connection of firstnode to second node.
start
10 20 30 NULL
temp
return 0;
}
linked list applications
Dynamic Memory Management. In allocationand
releasing memory at runtime
p1 2 2 3 1 7 0 NULL
p2=5x3 +5x+2
p2 5 3 5 1 2 0 NULL
P 5 3 2 2 8 1 9 0 NULL
Polynomials using Linked List: node
structure
node Address of
Coefficient power next node
struct node
{
int coeff;
int pow;
node *next;
}
Assignment 1
write a program to add two polynomials. usinglinked
list as representation of polynomials
Deadline 2-11-2019