19. Remove Nth Node From End of List
来源:互联网 发布:linux进程消失查日志 编辑:程序博客网 时间:2024/06/04 01:20
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个节点,通过两个指针,可以巧妙地在一次遍历中完成删除操作,具体思路如图:
在处理两个指针的时候要小心边界情况,图中加了一个Dummy节点,处理起来更方便。
/** * 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 dummyNode = ListNode(0); ListNode* dummy = &dummyNode; //把DummyNode放在链表开头 dummy->next = head; ListNode* first = dummy; ListNode* second = dummy; for (int i = 0; i < n + 1; i++) { second = second->next; } while (second) { first = first->next; second = second->next; } first->next = first->next->next; //这里注意要返回head,不是dummy return dummy->next; }};
阅读全文
0 0
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node from End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- sql server学习笔记-day2
- mysql查询最大连续出现天数
- MySql数据库表名、列名、别名区分大小写
- WHQL徽标认证
- 移动APP服务端API设计应该考虑到的问题
- 19. Remove Nth Node From End of List
- 专题 线段树B(最大值更新)
- Python2.0 模块大全
- AC的第一道省赛题目代码
- 跑步爱天天(欧拉序入门)
- Android面试题总结(三)
- Vijos P1659 河蟹王国
- Windows下安装Elasticsearch 5.0.0遇到的问题
- Win10---Redis 安装及常用命令