aboutsummaryrefslogtreecommitdiff
path: root/remove_nth_node.c
blob: 216f3ac3c16a66b6d781c1d372645dff6f43993c (plain)
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
// 19. Remove Nth Node From End of List
#include "leetcode.h"

/*
 * given the 'head' of a linked list, remove the n'th node from the end of the
 * list and return its head
 */

struct ListNode {
  int val;
  struct ListNode *next;
};

int get_len(struct ListNode *head) {
  struct ListNode *traverse = head;
  int n = 0;
  while (traverse) {
    traverse = traverse->next;
    n++;
  }
  return n;
}

struct ListNode *removeNthFromEnd(struct ListNode *head, int n) {
  int len = get_len(head);
  if (len == 1 && n == 1)
    return NULL;
  if (len == n)
    return head->next;
  int del_idx = len - n - 1;
  struct ListNode *traverse = head;
  while (del_idx) {
    traverse = traverse->next;
    del_idx--;
  }
  traverse->next = traverse->next->next;
  return head;
}