【LeetCode-19】Remove Nth Node From End of List(C++)
来源:互联网 发布:js统计网站访问量 编辑:程序博客网 时间:2024/05/22 00:32
题目要求:给出一个单链表,要求删除该单链表中从后面数的第n个节点。
解决方法:
1. 首先遍历链表,得到链表中的节点个数num。则num-n+1就是从头开始数的需要删除的节点位置。然后再从头开始遍历到第num-n个节点p2,用p2->next=p2->next->next;删除掉第num-n+1个节点。
/** * 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) { if(n==0) return head; ListNode* p1=head; ListNode* p2=head; int num=1; while(p1->next!=NULL){ num++; p1=p1->next; } if(num==n){ return head->next; } for(int i=1;i<num-n;i++){ p2=p2->next; } p2->next=p2->next->next; return head; }};
2. 上面这种方式对链表遍历了两次,下面有一种只对链表遍历一次的方式。就是设置两个指针,第一个指针从链表头结点开始遍历向前走n-1步,第二个指针保持不动。从第n步开始,第二个指针也开始从链表的头指针开始遍历。由于两个指针的距离始终保持在n-1,当第一个指针到达链表尾节点时,第二个指针刚好指向倒数第k个节点。
注意考虑各种非正常输入情况:如head为空指针,k小于等于0,链表中节点个数小于k等各种正常的输入。
/** * 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) { if(head==NULL||n<=0) return NULL; ListNode *p1=head,*p2=head; for(int i=0;i<n-1;i++){ if(p1->next!=NULL) p1=p1->next; else return NULL; } ListNode* tem; while(p1->next!=NULL){ p1=p1->next; tem=p2; p2=p2->next; } if(p2==head){ tem=p2->next; delete p2; p2=NULL; return tem; } tem->next=p2->next; delete p2; p2=NULL; return head; }};
0 0
- 【LeetCode-19】Remove Nth Node From End of List(C++)
- [C++]LeetCode: 4 Remove Nth Node From End of List
- [leetcode-]Remove Nth Node From End of List(C)
- 【C++】【LeetCode】19. Remove Nth Node From End of List
- Leetcode c语言-Remove Nth Node From End of List
- [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
- top 命令显示 CPU 的信息是从哪里获取?
- ios开发细节
- 各种遍历总结
- ajax提交form表单 js
- 求反射向量
- 【LeetCode-19】Remove Nth Node From End of List(C++)
- iOS xcode模拟器卡顿
- 淘宝购物车前端(JS和Angularjs版本)
- lua实现以字符串内容写入文件,成功返回 true,失败返回 false读取文件内容
- JAVA-正则表达式2
- IDEA2016 license server 激活
- Swift:邮箱网址手机号码等正则判断
- Unity3D游戏开发框架-创建txt文件,管理prefab路径
- Linux中Vi和Vim区别