19. Remove Nth Node From End of List题解
来源:互联网 发布:php curl post提交 编辑:程序博客网 时间:2024/05/22 03:07
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.
Subscribe to see which companies asked this question.
题目意思:
给你一个链表,去除掉倒数第n个节点。
解析:
设两个指针 p; q,让 q 先走 n 步,然后 p 和 q 一起走,直到 q 走到尾节点,删除 p->next 即可。
源代码:
#include <iostream>#include <stdio.h>#include <algorithm>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) { if (head == NULL || n <= 0){ return head; } ListNode *dummy = (ListNode*)malloc(sizeof(ListNode)); dummy->next = head; ListNode *temp = NULL; ListNode *pre = dummy,*cur = dummy; //cur先走N步 for(int i = 0;i < n;i++){ cur = cur->next; } //同步前进直到cur到最后一个节点 while(cur->next != NULL){ pre = pre->next; cur = cur->next; } //删除pre->next temp = pre->next; pre->next = temp->next; delete temp; return dummy->next; }};int main() { Solution solution; int A[] = {1,2,3,4,5}; ListNode *head = (ListNode*)malloc(sizeof(ListNode)); head->next = NULL; ListNode *node; ListNode *pre = head; for(int i = 0;i < 5;i++){ node = (ListNode*)malloc(sizeof(ListNode)); node->val = A[i]; node->next = NULL; pre->next = node; pre = node; } head = solution.removeNthFromEnd(head->next,4); while(head != NULL){ printf("%d ",head->val); head = head->next; } return 0;}
阅读全文
0 0
- Leetcode题解 19. Remove Nth Node From End of List
- 19. 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
- Lintcode174 Remove Nth Node From End of List solution 题解
- leetcode题解-328. Odd Even Linked List && 19. 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
- 算法课第17周第1题——133. Clone Graph
- 从零开始构建部署上线Node.js+Express+Bootstrap+Jade响应式网站应用—RSPT丨留学生活第一站(五)
- Linux-----线程互斥量与死活锁
- 判断数组为空array==null||array.length==0
- css中关于搜索框或按钮获得焦点时外边框变蓝的处理
- 19. Remove Nth Node From End of List题解
- 提升C++程序效率中的10个技巧
- FTP的搭建过程,以及遇到的坑
- fcntl.h函数库的常用函数使用
- poj 动态规划之1125 Stockbroker Grapevine
- 【MySQL】1130- Host“XXX” is not allowed to connect to this MySql server
- web.py 十分钟创建简易博客
- 享元模式
- mkfifo函数使用