LeetCode 19. Remove Nth Node From End of List(链表)
来源:互联网 发布:autodesk 设计造型软件 编辑:程序博客网 时间:2024/05/03 19:30
LeetCode 19. Remove Nth Node From End of List(链表)
- LeetCode 19 Remove Nth Node From End of List链表
- 问题描述
- 解题思路
- 参考代码
- By Scarb
- Scarb’s Blog
Tags:
- Linked List
- Two Pointers
问题描述
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个数字并且返回这个链表。
解题思路是使用两个指针,第一个指针遍历链表,第二个指针在第一个指针的前n-1个位置,当第一个指针遍历到链表结尾,第二个指针所在的位置就是第n-1个结点,此时可以删除第n个结点。
需要使用一个虚拟结点,放在链表的开头来处理边界情况。
参考代码
#include <iostream>using namespace std;struct ListNode { int val; ListNode *next; ListNode(int x): val(x), next(NULL) {}};class Solution{public: ListNode* removeNthFromEnd(ListNode *head, int n) { ListNode *dummy = new ListNode(0); dummy->next = head; ListNode *p1 = dummy; ListNode *p2 = dummy; for (int i = 0; i < n + 1; ++i) { p1 = p1->next; } while (p1 != NULL) { p1 = p1->next; p2 = p2->next; } //cout << p2->val << endl; p2->next = p2->next->next; return dummy->next; }};int main(){ ListNode *l1 = new ListNode(1); ListNode *l2 = new ListNode(2); ListNode *l3 = new ListNode(3); ListNode *l4 = new ListNode(4); ListNode *l5 = new ListNode(5); l1->next = l2; l2->next = l3; l3->next = l4; l4->next = l5; Solution sl = Solution(); ListNode *temp = sl.removeNthFromEnd(l1, 2); while (temp != NULL) { cout << temp->val << " "; temp = temp->next; } system("pause"); return 0;}
阅读全文
0 0
- [leetcode] 【链表】19. Remove Nth Node From End of List
- LeetCode 19. Remove Nth Node From End of List(链表)
- 19. Remove Nth Node From End of List leetcode list
- [LeetCode]19.Remove Nth Node From End of List
- LeetCode 19. Remove Nth Node From End of List
- 19. Remove Nth Node From End of List Leetcode Python
- LeetCode --- 19. Remove Nth Node From End of List
- LeetCode 19.Remove Nth Node From End of List
- [Leetcode] 19. Remove Nth Node From End of List
- [leetcode] 19.Remove Nth Node From End of List
- <LeetCode OJ> 19. Remove Nth Node From End of List
- 19. Remove Nth Node From End of List LeetCode
- leetcode 19. Remove Nth Node From End of List
- [LeetCode OJ] 19. Remove Nth Node From End of List
- LeetCode 19. Remove Nth Node From End of List
- Leetcode:19. Remove Nth Node From End of List(JAVA)
- leetcode 19. Remove Nth Node From End of List
- Leetcode 19. Remove Nth Node From End of List
- ——谈VC++对象模型
- PostgreSQL查看数据库,索引,表空间大小
- poj 2528 Mayor's posters 线段树 染色问题
- Linux 物理页面的周转
- JSP页面跳转
- LeetCode 19. Remove Nth Node From End of List(链表)
- 欢迎使用CSDN-markdown编辑器
- 正则替换字符串为空
- js定时器用法详解——setTimeout()、setInterval()、clearTimeout()、clearInterval()
- Linux 从PCB的角度谈用户空间
- 00---基础知识
- java反射通过字段名获取set、get方法
- 告别CMD.windows终端神器conemu设置
- 页面滚动到指定位置