Skip to content

Instantly share code, notes, and snippets.

@adis-io
Last active January 12, 2022 13:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adis-io/aa5f1896ed1b1d5baad03ceff35f96bc to your computer and use it in GitHub Desktop.
Save adis-io/aa5f1896ed1b1d5baad03ceff35f96bc to your computer and use it in GitHub Desktop.
Remove Nth Node From End of List #leetcode #c
#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