File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ * Given a linked list, remove the nth node from the end of list and return its head.
3
+
4
+ * For example,
5
+
6
+ * Given linked list: 1->2->3->4->5, and n = 2.
7
+ * After removing the second node from the end, the linked list becomes 1->2->3->5.
8
+ *
9
+ * Note:
10
+ * Given n will always be valid.
11
+ * Try to do this in one pass.
12
+ * Created by supercoderx on 2017/8/9.
13
+ */
14
+ #include
15
+ #include
16
+ #include "../main.h"
17
+
18
+ struct ListNode * removeNthFromEnd (struct ListNode * head , int n ) {
19
+ if (head == NULL ) {
20
+ return head ;
21
+ }
22
+ struct ListNode * p = head , * q ;
23
+ int len = 0 , id , index = 0 ;
24
+ while (p != NULL ) {
25
+ len ++ ;
26
+ p = p -> next ;
27
+ }
28
+ id = len - n ;
29
+ p = head ;
30
+ if (id == 0 ) {
31
+ head = head -> next ;
32
+ free (p );
33
+ } else {
34
+ while (index != id - 1 ) {
35
+ p = p -> next ;
36
+ index ++ ;
37
+ }
38
+ q = p -> next ;
39
+ p -> next = id == len - 1 ? NULL : q -> next ;
40
+ free (q );
41
+ }
42
+
43
+ return head ;
44
+
45
+ }
46
+
47
+ void testRemoveNthFromEnd () {
48
+
49
+ }
You can’t perform that action at this time.
0 commit comments