LeetCode_OJ【19】Remove Nth Node From End of List
来源:互联网 发布:移动老用户优惠淘宝 编辑:程序博客网 时间:2024/06/08 09:48
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.
一次遍历删除链表中倒数第N个元素。
思路很简单,设置两个指针p,q,中间间隔n-1个元素,当q指向链表结尾时,需要删除的元素正好是p的下一个元素。
在写算法的时候还是碰到了一些问题,比如有些测试用例需要删除的就是头结点,这种情况应该怎么处理呢,
后来参考了别人一些写法,在head结点前面设置dummy结点,算法结束后直接返回dummy.next即可。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode dummy = new ListNode(-1);dummy.next = head;ListNode p = dummy, q = dummy;for (int count = 1; q.next != null; q = q.next, count++) {if (count > n)p = p.next;}p.next = p.next.next;return dummy.next; }}
0 0
- LeetCode_OJ【19】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
- CentOS学习7_CentOS下安装Libreoffice
- nodejs学习
- linux的任务前后台管理(bg和fg命令)
- 关于Join的结果问题
- flash builder4.7 找不到IOS设备解决办法
- LeetCode_OJ【19】Remove Nth Node From End of List
- HTTPS原理详解
- Skew Binary-1565
- Linux-CentOS 7 修改屏幕分辨率
- UIKeyboardTypeNumberPad 数字键盘自定义按键
- VS2005格式化代码
- 初探 Qt Opengl【2】
- Android SDK在线更新镜像服务器
- FingerGestures研究院之初探Unity手势操作(一)