Linked List Assignment
Linked List Assignment
Linked List Assignment
33
DATA STRUCTURE
Linked List
void create (int A[], int n) {
int i;
struct Node *t, *last;
first = (struct Node *)malloc(sizeof(struct Node));
first -> data = A[0];
first -> next = NULL;
last = first;
for (i = 1; i < n; i ++) {
t = (struct Node*)malloc(sizeof(struct Node));
t -> data = A[i];
t -> next = NULL;
last -> next = t;
last = t;
}
}
/* Display function */
void Display(struct Node *p) {
while (p != NULL)
{
printf("%d ",p -> data);
p = p -> next;/* code */
}
}
void Display_r(struct Node *p) {
if (p != NULL) {
printf("%d ", p -> data);
Display_r (p ->next);
}
}
Data Structure Linked List Riddhi More, Roll no.33
void insertNode (struct Node *p, int index, int x) {
struct Node *t;
/* check vaidity of index*/
if (index < 0 || index > countNode(p))
return;
/* for inserting before first node */
if (index == 0) {
t -> next = first;
first = t;
}
/* for inserting other than before first node*/
else {
for (int i = 0; i < index - 1; i ++)
p = p -> next;
t -> next = p -> next;
p -> next = t;
}
}
Q2. Deleting an element from the list after the nth node.
/* deleting node after given index*/
int deleteAfterNode (struct Node *p, int index) {
struct Node *q = NULL;
int x = -1;
/*validate index*/
if (index < 0 || index > (countNode(p) + 1))
return -1;
for (int i = 0; i < index; i ++) {
q = p;
p = p -> next;
}
q -> next = p -> next;
x = p -> data;
free(p);
return x;
}
Data Structure Linked List Riddhi More, Roll no.33
int countNode (struct Node *p) {
int counter = 0;
while (p != NULL) {
counter ++;
p = p -> next;
}
return counter;
}
int countNode_r (struct Node *p) {
if (p == 0)
return 0;
else countNode_r(p -> next) + 1;
}
A = (int *)malloc(sizeof(int)*countNode(p));
/*copying*/
while (q != NULL) {
A[i] = q -> data;
q = q -> next;
i ++;
}
q = p;
i --;
while (q != NULL) {
q -> data = A[i];
q = q -> next;
i --;
}
}
Data Structure Linked List Riddhi More, Roll no.33
void reverseBySlide(struct Node *p) {
struct Node *q = NULL,*r = NULL;
while(p != NULL) {
r = q;
q = p;
p = p -> next;
q -> next = r;
}
first = q;
}
void reverseList_r(struct Node *q,struct Node *p) {
if (p) {
reverseList_r(p, p -> next);
p->next=q;
}
else
first = q;
}