-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinkedlist.c
More file actions
104 lines (104 loc) · 2.52 KB
/
linkedlist.c
File metadata and controls
104 lines (104 loc) · 2.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include <stdio.h>
#include<stdlib.h>
struct Node{
int data;
struct Node* next ;
};
void traverse (struct Node*ptr){
while(ptr != NULL){
printf("elemnts %d \n", ptr->data);
ptr = ptr -> next;
}
}
struct Node* insertatfirst(int data, struct Node*head){
struct Node *ptr = (struct Node*)malloc(sizeof(struct Node));
ptr -> next = head;
ptr -> data = data;
return ptr;
}
struct Node * insertatnext(struct Node *head, int data , int position){
struct Node*ptr = (struct Node*)malloc(sizeof(struct Node));
struct Node *p= head;
int i =0;
while(i != position - 1 ){
p= p ->next;
i++;
}
ptr -> data = data;
ptr -> next = p-> next;
p-> next = ptr;
return head;
}
struct Node*insertatend(struct Node*head, int data){
struct Node*ptr = (struct Node*)malloc(sizeof(struct Node));
struct Node*p = head ;
while (p ->next != NULL){
p = p-> next;
}
ptr ->data = data;
p ->next = ptr;
ptr -> next = NULL;
return head ;
}
struct Node*deletefirst (struct Node*head){
struct Node *ptr = head;
head = head ->next;
free(ptr);
return head ;
}
struct Node *deleteatindex(struct Node*head , int position){
struct Node*ptr = head;
struct Node*qtr = head->next ;
for(int i=0; i<position -1; i++){
ptr=ptr->next;
qtr=qtr->next;
}
ptr ->next = qtr ->next;
free (qtr);
return head ;
}
struct Node* deleteatend(struct Node*head){
struct Node*ptr = head;
struct Node*qtr = head->next;
while (qtr -> next != NULL){
qtr = qtr ->next;
ptr = ptr ->next;
}
ptr ->next = NULL;
free (qtr);
return head ;
}
int main(){
struct Node * head ;
struct Node * second ;
struct Node * third ;
head = (struct Node *)malloc (sizeof(struct Node));
second = (struct Node *)malloc (sizeof(struct Node));
third = (struct Node *)malloc (sizeof(struct Node));
head -> data = 7;
head -> next = second;
second -> data = 77;
second -> next = third;
third -> data = 777;
third -> next = NULL;
traverse(head);
printf("\n");
head = insertatfirst(34, head);
traverse(head);
printf("\n");
insertatnext(head, 89, 2);
traverse(head);
printf("\n");
head = insertatend(head , 78);
traverse(head);
printf("\n");
head = deletefirst(head);
traverse(head);
printf("\n");
deleteatindex(head , 0);
traverse(head);
printf("\n");
deleteatend(head);
traverse(head);
return 0;
}