-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinkedList10.c
115 lines (106 loc) · 2.84 KB
/
LinkedList10.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
// Merge two linked list
#include <stdio.h>
#include <stdlib.h>
struct ListNode
{
int val;
struct ListNode *next;
};
struct ListNode *mergeTwoLists(struct ListNode *l1, struct ListNode *l2)
{
if (l1 == NULL)
return l2;
if (l2 == NULL)
return l1;
struct ListNode *merged = NULL;
if (l1->val < l2->val)
{
merged = l1;
merged->next = mergeTwoLists(l1->next, l2);
}
else
{
merged = l2;
merged->next = mergeTwoLists(l1, l2->next);
}
return merged;
}
void displayList(struct ListNode *head)
{
while (head != NULL)
{
printf("%d -> ", head->val);
head = head->next;
}
printf("NULL\n");
}
int main()
{
struct ListNode *l1 = NULL, *l2 = NULL;
int choice, val;
do
{
printf("\nMenu:\n");
printf("1. Insert into list 1\n");
printf("2. Insert into list 2\n");
printf("3. Merge lists\n");
printf("4. Display list 1\n");
printf("5. Display list 2\n");
printf("6. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice)
{
case 1:
printf("Enter value to insert into list 1: ");
scanf("%d", &val);
struct ListNode *newNode1 = (struct ListNode *)malloc(sizeof(struct ListNode));
newNode1->val = val;
newNode1->next = NULL;
if (l1 == NULL)
l1 = newNode1;
else
{
struct ListNode *temp = l1;
while (temp->next != NULL)
temp = temp->next;
temp->next = newNode1;
}
break;
case 2:
printf("Enter value to insert into list 2: ");
scanf("%d", &val);
struct ListNode *newNode2 = (struct ListNode *)malloc(sizeof(struct ListNode));
newNode2->val = val;
newNode2->next = NULL;
if (l2 == NULL)
l2 = newNode2;
else
{
struct ListNode *temp = l2;
while (temp->next != NULL)
temp = temp->next;
temp->next = newNode2;
}
break;
case 3:
printf("Merged list: ");
displayList(mergeTwoLists(l1, l2));
break;
case 4:
printf("List 1: ");
displayList(l1);
break;
case 5:
printf("List 2: ");
displayList(l2);
break;
case 6:
printf("Exiting...\n");
break;
default:
printf("Invalid choice. Please try again.\n");
}
} while (choice != 6);
return 0;
}