leetcode--Remove Nth Node From End of List
来源:互联网 发布:测试网络稳定性软件 编辑:程序博客网 时间:2024/05/16 05:03
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. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { if(head==null) return null; ListNode p=head; for(int i=1;i<n;i++){ p=p.next; } ListNode s,q; s=null; q=head; while(p.next!=null){ s=q; q=q.next; p=p.next; } if(s==null) return q.next; s.next=q.next; q.next=null; q=null; return head; }}
c++:
/** * 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) return NULL; ListNode *p,*q,*s; p=head; // head已遍历,k从1开始 int k=1; while(k<n){ p=p->next; k++; } q=head; s=NULL; while(p->next){ s=q; q=q->next; p=p->next; } if(s){ s->next=q->next; delete q; return head; } // 一个节点,而且n==1 return q->next; }};
0 0
- LeetCode[Linked List]: Remove Nth Node From End of List
- 19. Remove Nth Node From End of List leetcode list
- [Leetcode]LeetCode 19:Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List
- [Leetcode] Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List
- leetcode 40: Remove Nth Node From End of List
- [LeetCode] Remove Nth Node From End of List
- Leetcode 19 Remove Nth Node From End of List
- [Leetcode] Remove Nth Node From End of List
- [LeetCode]Remove Nth Node From End of List
- LeetCode-Remove Nth Node From End of List
- [LeetCode] Remove Nth Node From End of List
- LeetCode 19: Remove Nth Node From End of List
- LeetCode - Remove Nth Node From End of List
- LeetCode | Remove Nth Node From End of List
- leetcode之Remove Nth Node From End of List
- 新年快乐 万事如意
- 面试 需要注意三种公司
- Java NIO 时不能邦定指定IP和端口
- Hibernate之查询中get()和load()的区别,list()和iterate()的区别
- 跳出多层循环
- leetcode--Remove Nth Node From End of List
- 自定义表格标签 JDBC查询时的显示转换
- 总结 20 个开发细节
- ARM寄存器介绍
- Linux 使用脚本安装Tomcat并部署程序
- 如何检测VPS宽带的上行速度和下行速度
- jQuery表单操作经验分享
- Linux 使用脚本安装MySQL数据库
- Linux下 卸载通过WINE安装的程序并且卸载source insight