【LeetCode】之Remove Nth Node From End of List
来源:互联网 发布:网络舆情情况汇报 编辑:程序博客网 时间:2024/04/28 15:16
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.
此题目的在于将一个链表的倒数第n个节点删除。
思路:
1.初始化两个节点p,q,p->next和q->next都指向head;
2.先让p节点往后走n步,然后让p,q节点同时往后走,直到p->next是NULL;
3.此时q->next就是链表的倒数第n个节点,删除这个节点,将链表连接起来;
4返回这个新链表就是最后的结果。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode dummy(-1); ListNode *p = &dummy; ListNode *q = &dummy; dummy.next = head;//p->next和q->next都指向head while(n--){//p节点往后走n步 p = p->next; } while(p->next){//p,q节点同时往后走,直到p->next是NULL p = p->next; q = q->next; } ListNode *temp = q->next;//q->next就是链表的倒数第n个节点 q->next = q->next->next;//链表连接起来 delete temp;//删除这个节点 return dummy.next; }};
0 0
- leetcode之Remove Nth Node From End of List
- LeetCode 之 Remove Nth Node From End of List
- LeetCode之Remove Nth Node From End of List
- LeetCode 之 Remove Nth Node From End of List
- LeetCode之Remove Nth Node From End of List
- 【LeetCode】之Remove Nth Node From End of List
- 【Leetcode】之Remove Nth Node From End of List
- leetcode之Remove Nth Node From End of List
- leetcode之Remove Nth Node From End of List
- LeetCode之19---Remove Nth Node From End of List
- leetcode:单链表之Remove Nth Node From End of List
- Leetcode 之 Remove Nth Node From End of List
- Leetcode之Remove Nth Node From End of List 问题
- LeetCode 之 Remove Nth Node From End of List
- LeetCode[Linked List]: Remove Nth Node From End of List
- 19. Remove Nth Node From End of List leetcode list
- [Leetcode]LeetCode 19:Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List
- docker常用命令
- 选择排序之堆排序(大顶堆)
- 自动提示和手动提示 VS2013与Eclipse中的设置
- Fuse安装和使用
- 2014腾讯、百度、阿里面试经验
- 【LeetCode】之Remove Nth Node From End of List
- Easyui+Spring+Mybatis完整示例(后台)
- 【JavaSE】day05_List集合_List排序_队列和栈
- Word Break && Word Break II
- C内存对齐
- 选择排序之直接选择排序
- Codeforces Round #186 (Div. 2) (ABCDE题解)
- 腾讯面试中最易被刷的几种表现求解答
- 开发工具-SVN