-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExam
150 lines (127 loc) · 4.07 KB
/
Exam
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Linked_List_Sort
{
class Program
{
/* Link list node */
public class Node
{
public int data;
public Node next;
public Node(int d)
{
data = d;
next = null;
}
}
public class MergeLists
{
Node head;
/* Method to insert a node at
the end of the linked list */
public void addToTheLast(Node node)
{
if (head == null)
{
head = node;
}
else
{
Node temp = head;
while (temp.next != null)
temp = temp.next;
temp.next = node;
}
}
/* Method to print linked list */
void printList()
{
Node temp = head;
while (temp != null)
{
Console.Write(temp.data + " ");
temp = temp.next;
}
Console.WriteLine();
Console.ReadLine();
}
// Driver Code
public static void Main(String[] args)
{
/* Let us create two sorted linked
lists to test the methods
Created lists:
Head1: 4, 8, 15, 19
Head2: 7, 9, 10, 16
*/
MergeLists Head1 = new MergeLists();
MergeLists Head2 = new MergeLists();
Head1.addToTheLast(new Node(4));
Head1.addToTheLast(new Node(8));
Head1.addToTheLast(new Node(15));
Head1.addToTheLast(new Node(19));
Head2.addToTheLast(new Node(7));
Head2.addToTheLast(new Node(9));
Head2.addToTheLast(new Node(10));
Head2.addToTheLast(new Node(16));
Head1.head = new Gfg().sortedMerge(Head1.head,
Head2.head);
Head1.printList();
}
}
public class Gfg
{
/* Takes two lists sorted in
increasing order, and splices
their nodes together to make
one big sorted list which is
returned. */
public Node sortedMerge(Node headA, Node headB)
{
/* a dummy first node to
hang the result on */
Node dummyNode = new Node(0);
/* tail points to the
last result node */
Node tail = dummyNode;
while (true)
{
/* if either list runs out,
use the other list */
if (headA == null)
{
tail.next = headB;
break;
}
if (headB == null)
{
tail.next = headA;
break;
}
/* Compare the data of the two
lists whichever lists' data is
smaller, append it into tail and
advance the head to the next Node
*/
if (headA.data <= headB.data)
{
tail.next = headA;
headA = headA.next;
}
else
{
tail.next = headB;
headB = headB.next;
}
/* Advance the tail */
tail = tail.next;
}
return dummyNode.next;
}
}
}
}