[leetcode 19] Remove Nth Node From End of List
来源:互联网 发布:iphonex监控预约软件 编辑:程序博客网 时间:2024/04/30 04:03
Question:
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无效情况。
因为给的是倒数第n位,所以利用两个指针就可以了,初始化为head,第一个指针q比第二个指针p多走n步。如果q先走n步后为NULL,则说明要删除的为正数第一个节点,直接将head = head->next即可,否则,p q一起走,知道q->next为NULL,p指向的为要删除节点的前一个节点。
代码如下:
<span style="font-size:14px;">/** * 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 *p,*q; p = head; q = head; while(n--){ q = q->next; } if(q != NULL){ while(q->next != NULL){ p = p->next; q = q->next; } p->next = p->next->next; } else{ head = head->next; } return head; }};</span>
0 0
- [Leetcode]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, Easy] 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 Solutions
- 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 | #19 Remove Nth Node From End of List
- leetcode.19----------Remove Nth Node From End of List
- [Leetcode 19, Easy] 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 19 Remove Nth Node From End of List
- leetcode 19 Remove Nth Node From End of List
- 第十三章 RememberMe
- Codeforces 597C Subsequences 【树状数组优化DP】
- 第十四章 SSL
- 遍历一个文件夹下面的文件(半原创)
- 在64位Ubuntu 14.04 LTS 中安装praat
- [leetcode 19] Remove Nth Node From End of List
- 第十五章 单点登录
- 第十六章 综合实例
- Java 声明变量名的规则
- Java学习中遇到的问题01_IO流
- 第十七章 OAuth2集成
- android面试攻略(2)
- Android源码阅读与理解(一):开篇
- 第十八章 并发登录人数控制