Skip to content

Commit 47278c9

Browse files
committed
Add C Solutions for 3 problems: 141-Linked-List-Cycle.c, 206-Reverse-Linked-List.c and 21-Merge-Two-Sorted-Lists
1 parent 608f0f8 commit 47278c9

File tree

3 files changed

+105
-0
lines changed

3 files changed

+105
-0
lines changed

Diff for: c/141-Linked-List-Cycle.c

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
2+
/**
3+
* Definition for singly-linked list.
4+
* struct ListNode {
5+
* int val;
6+
* struct ListNode *next;
7+
* };
8+
*/
9+
10+
bool Traverse(struct ListNode* slow, struct ListNode* fast) {
11+
12+
if (slow == NULL || slow -> next == NULL) {
13+
return false;
14+
}
15+
16+
if (fast == NULL || fast -> next == NULL) {
17+
return false;
18+
}
19+
20+
if (slow == fast) {
21+
return true;
22+
}
23+
return Traverse(slow -> next, fast -> next -> next);
24+
}
25+
26+
27+
bool hasCycle(struct ListNode *head) {
28+
29+
if (head == NULL) {
30+
return false;
31+
}
32+
33+
return Traverse(head, head -> next);
34+
35+
}

Diff for: c/206-Reverse-Linked-List.c

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
2+
/**
3+
* Definition for singly-linked list.
4+
* struct ListNode {
5+
* int val;
6+
* struct ListNode *next;
7+
* };
8+
*/
9+
10+
11+
struct ListNode* reverseList(struct ListNode* head){
12+
13+
if (head == NULL) {
14+
return NULL;
15+
} else if (head -> next == NULL) {
16+
return head;
17+
}
18+
19+
struct ListNode* lastNode = reverseList(head -> next);
20+
head -> next -> next = head;
21+
head -> next = NULL;
22+
return lastNode;
23+
24+
}

Diff for: c/21-Merge-Two-Sorted-Lists.c

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
2+
/**
3+
* Definition for singly-linked list.
4+
* struct ListNode {
5+
* int val;
6+
* struct ListNode *next;
7+
* };
8+
*/
9+
10+
11+
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2){
12+
13+
if (list1 == NULL && list2 == NULL) {
14+
return NULL;
15+
} else if (list1 != NULL && list2 == NULL) {
16+
return list1;
17+
} else if (list2 != NULL && list1 == NULL) {
18+
return list2;
19+
}
20+
21+
struct ListNode* temp_node = NULL;
22+
23+
if (list1 -> val < list2 -> val) {
24+
temp_node = list1;
25+
list1 = list1 -> next;
26+
} else {
27+
temp_node = list2;
28+
list2 = list2 -> next;
29+
}
30+
31+
struct ListNode* root = temp_node;
32+
33+
while((list1 != NULL) || (list2 != NULL)) {
34+
35+
if ((list2 == NULL) || ((list1 != NULL) && (list1 -> val < list2 -> val))) {
36+
temp_node -> next = list1;
37+
list1 = list1 -> next;
38+
} else {
39+
temp_node -> next = list2;
40+
list2 = list2 -> next;
41+
}
42+
temp_node = temp_node -> next;
43+
}
44+
45+
return root;
46+
}

0 commit comments

Comments
 (0)