-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathswap_nodes.c
More file actions
83 lines (82 loc) · 1.74 KB
/
Copy pathswap_nodes.c
File metadata and controls
83 lines (82 loc) · 1.74 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
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *next;
};
struct node *head=NULL;
struct node *create(struct node *head,int i){
struct node *ptr;
ptr=(struct node *) malloc(sizeof(struct node));
struct node *p;
printf("Enter value[%d] of list:",i);
scanf("%d",&ptr->data);
ptr->next=NULL;
if(head==NULL){
head=ptr;
p=head;
return(head);
}
else{
p->next=ptr;
p=ptr;
return(head);
}
}
void swap_node(struct node **ptr,int x,int y){
if(x==y){
return;
}
struct node *currx=*ptr,*prevx=NULL;
while(currx&&currx->data!=x){
prevx=currx;
currx=currx->next;
}
struct node *curry=*ptr,*prevy=NULL;
while(curry&&curry->data!=y){
prevy=curry;
curry=curry->next;
}
if(currx==NULL||curry==NULL){
return;
}
if(prevx!=NULL){
prevx->next=curry;
}
else{
*ptr=curry;
}
if(prevy!=NULL){
prevy->next=currx;
}
else{
*ptr=currx;
}
struct node *p=curry->next;
curry->next=currx->next;
currx->next=p;
}
void print(struct node *ptr){
int i=1;
while(ptr!=NULL){
printf("Value at Node[%d]:%d\n",i,ptr->data);
i++;
ptr=ptr->next;
}
}
int main(){
int i,n,data,pos;
printf("Enter size of linked list:");
scanf("%d",&n);
for(i=0;i<n;i++){
head=create(head,i+1);
}
print(head);
int x,y;
printf("Enter which number for swapping from linked list:\n");
printf("Enter 2 numbers:\n");
scanf("%d%d",&x,&y);
swap_node(&head,x,y);
print(head);
return 0;
}