-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathconcatenate-linked-lists.c
124 lines (97 loc) · 2.13 KB
/
concatenate-linked-lists.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
/*
Copyright (C) Deepali Srivastava - All Rights Reserved
This code is part of DSA course available on CourseGalaxy.com
*/
#include<stdio.h>
#include<stdlib.h>
struct node
{
int info;
struct node *link;
};
struct node *createList(struct node *start);
void displayList(struct node *start);
struct node *insertInBeginning(struct node *start,int data);
void insertAtEnd(struct node *start,int data);
struct node *concatenate( struct node *start1,struct node *start2);
main()
{
struct node *start1=NULL,*start2=NULL;
start1=createList(start1);
start2=createList(start2);
printf("First list is : "); displayList(start1);
printf("Second list is : "); displayList(start2);
start1=concatenate(start1, start2);
printf("Concatenated list is : "); displayList(start1);
}
struct node *concatenate( struct node *start1,struct node *start2)
{
struct node *p;
if(start1==NULL)
{
start1=start2;
return start1;
}
if(start2==NULL)
return start1;
p=start1;
while(p->link!=NULL)
p=p->link;
p->link=start2;
return start1;
}
struct node *createList(struct node *start)
{
int i,n,data;
printf("Enter the number of nodes : ");
scanf("%d",&n);
if(n==0)
return start;
printf("Enter the first element to be inserted : ");
scanf("%d",&data);
start=insertInBeginning(start,data);
for(i=2; i<=n; i++)
{
printf("Enter the next element to be inserted : ");
scanf("%d",&data);
insertAtEnd(start,data);
}
return start;
}/*End of createList()*/
struct node *insertInBeginning(struct node *start,int data)
{
struct node *temp;
temp=(struct node *)malloc(sizeof(struct node));
temp->info=data;
temp->link=start;
start=temp;
return start;
}
void insertAtEnd(struct node *start,int data)
{
struct node *p,*temp;
temp=(struct node *)malloc(sizeof(struct node));
temp->info=data;
p=start;
while(p->link!=NULL)
p=p->link;
p->link=temp;
temp->link=NULL;
}
void displayList(struct node *start)
{
struct node *p;
if(start==NULL)
{
printf("List is empty\n");
return;
}
printf("List is : ");
p=start;
while(p!=NULL)
{
printf("%d ",p->info);
p=p->link;
}
printf("\n");
}/*End of displayList() */