LeetCode题解之Remove Nth Node From End of List

Posted 山里的小勇子

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode题解之Remove Nth Node From End of List相关的知识,希望对你有一定的参考价值。

1、题目描述

 

2、问题分析

直接计算,操作。

3、代码

 1 ListNode* removeNthFromEnd(ListNode* head, int n) {
 2         if (head == NULL)
 3             return head;
 4         int len = 0;
 5         ListNode *p = head;
 6         while (p != NULL) {
 7             len++;
 8             p = p->next;
 9         }
10         
11         int step = len - n;
12         if (step == 0)
13             return head->next;
14         p = head;
15         while (--step) {
16             p = p->next;
17         }
18         
19         ListNode *tmp = p->next->next;
20         p->next = tmp;
21         
22         
23         return head;
24         
25         
26     }

 

以上是关于LeetCode题解之Remove Nth Node From End of List的主要内容,如果未能解决你的问题,请参考以下文章