Remove Nth Node From End of List
来源:互联网 发布:sopcast这款网络电视 编辑:程序博客网 时间:2024/06/16 22:09
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.
/** * 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 *l1=head; ListNode *l2=head; int step=1;ListNode *l3=head;if(l1->next==NULL&&n==1) return NULL; while(l2->next!=NULL||step<=n-1){ //l1=l1->next; l2=l2->next; if(step>n-1) l1=l1->next; if(step>n) l3=l3->next; step++;}if(l1==head){return l1->next;}if(l3->next!=NULL)l3->next=l3->next->next;elsel3->next=NULL;return head; }};
第二版:
/** * 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) { return NULL; } ListNode * Nhead = new ListNode(0); Nhead -> next = head; ListNode* f = Nhead; ListNode* s = Nhead; int step = 1; while(f -> next != NULL) { f = f -> next; if(step > n) { s = s -> next; } ++ step; } ListNode *tmp = s -> next; tmp = tmp -> next; s -> next = tmp; return Nhead -> next; }};
0 0
- 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
- 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
- 天声人語 20150812
- Android Studio系列教程1一--下载与安装
- linux vi选中文本方法
- android build 过程 (ramdisk.img、sytem.img、userdata.img)和 启动过程简单分析
- 杨氏矩阵第K小值/两个数组元素之和最小值
- Remove Nth Node From End of List
- VB查询ACCESS数据库内容
- Ubuntu下使用SQLCipher命令行对db加密
- HTMLParser半自动解析网页的应用
- 在linux上部署Java项目
- Gaming鼠标术语解析
- Linux里如何查找文件内容
- String s 与String s1 = new String();的本质区别及==与equals的区别。
- android listvieew PullToRefreshListView设置setOnTouchListener()失效