Skip to content

Commit

Permalink
Add C Solutions for 3 problems: 141-Linked-List-Cycle.c, 206-Reverse-…
Browse files Browse the repository at this point in the history
…Linked-List.c and 21-Merge-Two-Sorted-Lists
  • Loading branch information
th-blitz committed Aug 22, 2022
1 parent 608f0f8 commit 47278c9
Show file tree
Hide file tree
Showing 3 changed files with 105 additions and 0 deletions.
35 changes: 35 additions & 0 deletions c/141-Linked-List-Cycle.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/

bool Traverse(struct ListNode* slow, struct ListNode* fast) {

if (slow == NULL || slow -> next == NULL) {
return false;
}

if (fast == NULL || fast -> next == NULL) {
return false;
}

if (slow == fast) {
return true;
}
return Traverse(slow -> next, fast -> next -> next);
}


bool hasCycle(struct ListNode *head) {

if (head == NULL) {
return false;
}

return Traverse(head, head -> next);

}
24 changes: 24 additions & 0 deletions c/206-Reverse-Linked-List.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/


struct ListNode* reverseList(struct ListNode* head){

if (head == NULL) {
return NULL;
} else if (head -> next == NULL) {
return head;
}

struct ListNode* lastNode = reverseList(head -> next);
head -> next -> next = head;
head -> next = NULL;
return lastNode;

}
46 changes: 46 additions & 0 deletions c/21-Merge-Two-Sorted-Lists.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/


struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2){

if (list1 == NULL && list2 == NULL) {
return NULL;
} else if (list1 != NULL && list2 == NULL) {
return list1;
} else if (list2 != NULL && list1 == NULL) {
return list2;
}

struct ListNode* temp_node = NULL;

if (list1 -> val < list2 -> val) {
temp_node = list1;
list1 = list1 -> next;
} else {
temp_node = list2;
list2 = list2 -> next;
}

struct ListNode* root = temp_node;

while((list1 != NULL) || (list2 != NULL)) {

if ((list2 == NULL) || ((list1 != NULL) && (list1 -> val < list2 -> val))) {
temp_node -> next = list1;
list1 = list1 -> next;
} else {
temp_node -> next = list2;
list2 = list2 -> next;
}
temp_node = temp_node -> next;
}

return root;
}

0 comments on commit 47278c9

Please sign in to comment.