-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReverseLinkedList.c
103 lines (88 loc) · 1.79 KB
/
ReverseLinkedList.c
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
#include<stdio.h>
#include<stdlib.h>
typedef struct Node{
int data ;
struct Node* next;
} node;
node* createLinkedList(node* head){
head=NULL;
return head;
}
void display(struct Node *ptr){
while (ptr != NULL)
{
printf("%d ", ptr->data);
ptr = ptr->next;
}
}
struct Node* add(struct Node *head,int val){
struct Node* p=(struct Node*)malloc(sizeof(struct Node));
p->data=val;
p->next=NULL;
struct Node* temp;
if(head==NULL){
head=p;
}else if(head->next==NULL){
head->next=p;
}else{
temp=head;
while(temp->next != NULL){
temp=temp->next;
}
temp->next=p;
}
return head;
}
int len(struct Node *head){
if(head==NULL){
return 0;
}else if(head->next==NULL){
return 1;
}else{
int count=1;
struct Node* temp=head;
while(temp->next != NULL){
temp=temp->next;
count++;
}
return count;
}
}
node* reverse(node* head){
if(head ==NULL || head->next==NULL){
return head;
}
node* p=head;
node* q=head->next;
node* r=head->next->next;
while(q != NULL){
q->next=p;
p=q;
q=r;
if(r==NULL){
q=r;
}else{
r=r->next;
}
}
head->next=NULL;
head=p;
return head;
}
int main(){
int n,item;
node* head;
head=createLinkedList(head);
printf("Number of Elements you want to add to your list\n");
scanf("%d",&n);
for(int i=0;i<n;i++){
printf("Enter the number to add in Linked List\n");
scanf("%d",&item);
head=add(head,item);
}
display(head);
printf("\n");
head=reverse(head);
display(head);
return 0;
}