Last active
January 12, 2022 13:42
-
-
Save adis-io/aa5f1896ed1b1d5baad03ceff35f96bc to your computer and use it in GitHub Desktop.
Remove Nth Node From End of List #leetcode #c
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
struct ListNode { | |
int val; | |
struct ListNode *next; | |
}; | |
struct ListNode* createNodeList(int arr[], int numSize); | |
struct ListNode* removeNthFromEnd(struct ListNode* head, int n); | |
void displayList(); | |
void main() { | |
struct ListNode *head; | |
int arr[] = {1, 2, 3, 4, 5}; | |
head = createNodeList(arr, (sizeof(arr) / sizeof(*arr))); | |
displayList(head); | |
head = removeNthFromEnd(head, 2); | |
printf("\n"); | |
displayList(head); | |
} | |
struct ListNode* createNodeList(int arr[], int numSize) { | |
struct ListNode *head, *previous, *current; | |
head = previous = current = (struct ListNode *) malloc(sizeof(struct ListNode)); | |
previous->val = arr[0]; | |
previous->next = NULL; | |
for (int i = 1; i < numSize; i++, previous = previous->next) { | |
current = (struct ListNode *) malloc(sizeof(struct ListNode)); | |
current->val = arr[i]; | |
current->next = NULL; | |
previous->next = current; | |
} | |
return head; | |
} | |
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) { | |
struct ListNode *fast = head; | |
struct ListNode *slow = head; | |
int i = 0; | |
while (fast->next != NULL) { | |
if (i >= n) { | |
slow = slow->next; | |
} | |
fast = fast->next; | |
i++; | |
} | |
if (i < n) { | |
head = head->next; | |
} else { | |
slow->next = slow->next->next; | |
} | |
return head; | |
} | |
void displayList(struct ListNode *head) { | |
struct ListNode *tmp; | |
tmp = head; | |
while(tmp != NULL) { | |
printf("%d, ", tmp->val); | |
tmp = tmp->next; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment