leetcode: (19) Remove Nth Node From End of List
来源:互联网 发布:小米3破解4g网络 编辑:程序博客网 时间:2024/06/06 07:44
【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.
方法一:题目要求删除倒数的第n个节点首先,必须就算出一共有多少节点,才能知道要删除的节点的位置,通过一次遍历,计算出总的节点数;
然后,再一次遍历到倒数第n个节点的前一个节点,然后进行删除操作;
其中要注意的是
1)n=总的节点数 时 ,此时要删除的节点为首指针,只需将head=head->next;即可
class Solution {public: ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode *cur,*p,*temp,*pre; p=head; cur=head; int count=0; while(p!=NULL) { p=p->next; count++; }temp=(ListNode *)malloc(sizeof(ListNode)); if (count==n) {head=head->next;;return head;} else { for(int i=0;i<count-n;i++) {pre=cur; cur=cur->next; } temp=pre->next; pre->next=temp->next; free(temp); } return head; }};
Runtime: 4 ms
方法二:由于倒数第n个点到头结点的距离=第n个点的距离到尾节点的距离,所以不必进行第一次遍历得出总的节点数.
public class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode curr = head; ListNode pre = head; for(int i = 0;i < n;i++) curr = curr.next; if(curr == null) return head.next; while(curr.next != null) { curr = curr.next; pre = pre.next; } pre.next = pre.next.next; return head; } }Runtime: 272 ms
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
- Java问题总结之1-2--超出数据类型取值范围
- Android学习
- The Euler function(hdoj --2824-欧拉函数)
- POJ题目分类进阶
- hdoj 1856 More is better
- leetcode: (19) Remove Nth Node From End of List
- mac下解决中文编码问题
- 2015-08-24 part3 uboot.bin烧录
- windows 下和linux下 用python监控文件夹内容变化
- 首篇
- *** Please tell me who you are.
- poj 1287 Networking 【MST】【练模板】
- svn cleanup failed 解决办法
- POJ - 1157 LITTLE SHOP OF FLOWERS