eetCode:Remove Nth Node From End of List

简介:

Given a linked list, remove the nth node from the end of list and return its head.

For example,

   Given linked list: 1->2->3->4->5, and n = 2.

   After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:
Given n will always be valid.
Try to do this in one pass.

主要难点是通过一趟遍历寻找链表倒数第k个元素,具体见代码注释                            本文地址

复制代码
 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode *removeNthFromEnd(ListNode *head, int n) {
12         //快指针先走n步,然后快慢指针一起走,块指针指向尾节点时,慢指针指向倒数第n个节点
13         ListNode* fast = head, *slow = head, *slowpre = NULL;
14         for(int i = 1; i < n; i++)fast = fast->next;
15         while(fast->next)
16         {
17             fast = fast->next;
18             slowpre = slow;
19             slow = slow->next;
20         }
21         if(slow == head)
22             head = head->next;
23         else
24             slowpre->next = slow->next;
25         delete slow;
26         return head;
27     }
28 };
复制代码





本文转自tenos博客园博客,原文链接:http://www.cnblogs.com/TenosDoIt/p/3667510.html,如需转载请自行联系原作者

目录
相关文章
|
5月前
Leetcode 19.Remove Nth Node From End of List
删除单链表中的倒数第n个节点,链表中删除节点很简单,但这道题你得先知道要删除哪个节点。在我的解法中,我先采用计数的方式来确定删除第几个节点。另外我在头节点之前额外加了一个节点,这样是为了把删除头节点的特殊情况转换为一般情况,代码如下。
19 0
|
23天前
List中的remove方法遇到报错不能删除以及四种解决办法点赞收藏
List中的remove方法遇到报错不能删除以及四种解决办法点赞收藏
16 0
|
27天前
使用List中的remove方法遇到数组越界
使用List中的remove方法遇到数组越界
16 2
|
5月前
避免list中remove导致ConcurrentModificationException
避免list中remove导致ConcurrentModificationException
20 0
|
10月前
for-each或迭代器中调用List的remove方法会抛出ConcurrentModificationException的原因
for-each循环遍历的实质是迭代器,使用迭代器的remove方法前必须调用一下next()方法,并且调用一次next()方法后是不允许多次调用remove方法的,为什么呢?接下来一起来看吧
55 0
List的remove操作一定要小心!
List的remove操作一定要小心!
LeetCode 19. 删除链表的倒数第N个节点 Remove Nth Node From End of List
LeetCode 19. 删除链表的倒数第N个节点 Remove Nth Node From End of List
LeetCode 203. Remove Linked List Elements
删除链表中等于给定值 val 的所有节点。
58 0
LeetCode 203. Remove Linked List Elements
LeetCode 82. Remove Duplicates from Sorted List II
给定已排序的链接列表,删除所有具有重复数字的节点,只留下原始列表中的不同数字。
72 0
LeetCode 82. Remove Duplicates from Sorted List II
|
Python
python list 中 remove 的骚操作/易错点
python list 中 remove 的骚操作/易错点
155 0
python list 中 remove 的骚操作/易错点