LeetCOde19. Remove Nth Node From End of List
来源:互联网 发布:辐射测试软件 编辑:程序博客网 时间:2024/05/06 05:10
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.
#include<cstdlib>#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) { int num=0,t=1,times=1; ListNode *p=head; while(p){ num++; p=p->next; } if(n>num) return head; if(n<=0) return head; if(n==num) {head=head->next; return head;} p=head; times = num-n; while(t<times){ p=p->next; ++t; } if(n==1){p->next=NULL;} else{ p->next=(p->next)->next;} return head; }};void main(){ ListNode L1(1); ListNode L2(2); ListNode L3(3); ListNode L4(4); ListNode L5(5); L1.next=&L2; //L2.next=&L3; //L3.next=&L4; //L4.next=&L5; ListNode *p; p=&L1; while(p->next){ cout<<(p->val)<<"->"; p=p->next; } cout<<(p->val)<<endl; Solution So; ListNode *res = So.removeNthFromEnd(&L1,1); ListNode *p2=res; while(p2->next){ cout<<(p2->val)<<"->"; p2=p2->next; } cout<<(p2->val)<<endl;}
0 0
- LeetCode19:Remove Nth Node From End of List
- [LeetCode19]Remove Nth Node From End of List
- leetcode19-Remove Nth Node From End of List
- LeetCode19——Remove Nth Node From End of List
- Leetcode19 Remove Nth Node From End of List
- LeetCode19:Remove Nth Node From End of List
- leetcode19---Remove Nth Node From End of List
- leetcode19. Remove Nth Node From End of List
- leetcode19.Remove Nth Node From End of List
- leetcode19:Remove Nth Node From End of List
- Leetcode19. Remove Nth Node From End of List
- leetcode19:Remove Nth Node From End of List
- Leetcode19 - Remove Nth Node From End of List(链表)
- leetcode19~Remove Nth Node From End of List
- LeetCOde19. Remove Nth Node From End of List
- LeetCode19. Remove Nth Node From End of List
- LeetCode19. Remove Nth Node From End of List
- LeetCode19:Remove Nth Node From End of List
- 阿里负责人揭秘面试潜规则
- 自守数定义:一个自然数的平方的尾数等于该数本身。例如:25=625,76=5776,9376=87909376,则25、76、9376均是自守数。试建立一个类Self,求出指定范围内的自守
- 历届试题 翻硬币 (蓝桥杯)
- CSDN 转载别人的文章
- hdu-1704-Rank(floyd-传递闭包)
- LeetCOde19. Remove Nth Node From End of List
- 深拷贝与浅拷贝
- Python根据AccessLog统计对应Url的点击量
- 二分函数用法
- Jsp的基本语法
- POJ 3101 Astronomy (数学)
- 编写一个通用程序,将二维数组含有最大元素的列与第0列元素对调。例如,原数组和调换后的目标数组为
- 【MySQL基础】触发器与本地化
- vs下opencv的人脸检测以及qt下dll的封装调用(四、qt下测试dll)