Linklist 1
Linklist 1
Insert at end
Inserts an element at the end of the list void insertend(int x) { Node *temp = head; while (temp -> link != NULL) temp = temp->link; Node *newer = new Node; newer->data = x; newer->link = NULL; temp->link = newer; } head 12 10
temp
newer
14
16
10
12
14
16
Assignment
Merge two lists. Delete all occurrences of a number from the list.
head
elements
rear
nodes
front
elements
Queue Operations
struct Queue
{ int info; Queue *link; }; Queue *front, *rear; rear = front = NULL;
front
rear
Queue Operations
bool empty()
{ if ( front==NULL) return TRUE; else return FALSE; }
Queue Operations
int remove()
{
if (empty()) { cout <<Queue underflow; exit(1); } Queue *temp = front; int x = front->info; front = front->link; if (front== NULL) rear = NULL; delete temp; return x;
rear
6 8
front temp
Queue Operations
Void insert(int x)
{
Queue *temp = new Queue; temp->info=x; temp->link = NULL; if (rear== NULL) front = temp; else rear->link = temp; rear = temp;
rear
temp
front
10
Circular List
Circular List: The tail of the list points back to the head
Circular List
There is no first and last node in circular list so we establish a first, last node by convention First Node
Last Node
2
Last
4 6
8
Implementation of Stack
struct Node { int info; Node *link; }; Node *last; last = NULL;
Stack Operations
bool empty() { if (last == NULL) return TRUE; else return FALSE: }
PUSH
void push(int x)
{ Node * temp = new Node; temp->info = x; if (last == NULL) last = temp; else temp->link = last->link; } last->link = temp; }
last
temp
POP
int pop()
{ int x; Node *temp; if (empty()) {cout << Empty Stack; exit(1);} temp = last->link; x = temp->info; if (temp == last) last = NULL; else last->link = temp->link; delete temp; return x; }
last
1 temp
last
temp
DELAFTER()
void delafter(Node *p)
{ int x; Node *temp; if (p==NULL || p==p->link) { cout << void deletion; return; } temp = p->link; x = p->info; p->link = temp->next; p delete temp;
temp
last
Josephus Problem
read n; read(name); while (name != END) { insert name on the circular list; read(name); } while (there is more than one node on the list) { count through n-1 nodes on the list; print the name in the nth node; delete nth node } Print the name of the only node on the list
Doubly-Linked Lists
Each node contains two pointers, one to its successor and one to its predecessor. Doubly linked list can be linear or circular.
left
NULL
info
right
88
42
109
NULL
head 88 42 109
Doubly link list can be implemented using lists. Each node contains left, right pointers and info part. struct node { int info; node *left, *right; };
Delete
int Delete(Node *p) { Node *q, *r; int x; if (p==NULL) { cout << void deletion; return;} x = p->info; q = p->left; r = p->right; q->right = r; r->left = q; delete p; }
Insertright
void insertright(Node *p, int x) { Node *q, *r; if (p==NULL) { cout << void insertion; return;} q = new node; q->info = x; r = p->right; r->left = q; q->right = r; q->left = p; p->right = q; }