Remove Nth Node From End of List
来源:互联网 发布:连锁店用什么软件 编辑:程序博客网 时间:2024/05/18 19:42
原题地址:点我传送
挺有意思的一道题,要删除链表中的倒数第n个值。最简单的就是直接一次循环找到末尾,然后再一次循环到倒数第n-1个删除即可。但是这样做难免给人浪费的感觉,其实只用一次循环也可以做成。只需要使用两个指针,一个是先从头指针出发往后n-1个的位置,另一个则是头指针开始。当走在前面的指针到末端时,后面的指针跳过一个位置就把那个位置即倒数第n个值给删除了。
但这样做的问题是删除第一个和最后一个的时候是特殊情况,需要单独拿出来处理。
Java:
/** * 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 p = head; ListNode q = p; for(int i=1;i<=n;i++) { q=q.next; } if(q==null) //1st { return head.next; } while(q.next!=null) { q=q.next; p=p.next; } if(p.next!=null) { p.next = p.next.next; } else // last { p.next = null; } return head; }}
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
- Nosql 理解篇+实战篇 五 NoSQL一致性解决方案
- 希尔排序
- SpringMVC-接收请求参数和页面传参
- 02:最大子矩阵
- 水平进度条
- Remove Nth Node From End of List
- c++学习笔记--下标重载函数
- Android PopupWindow使用方法小结
- 全面的MIME类型对照表
- 学员心声(四)
- Java类加载机制
- c++ primer 12.1.2练习
- android进行异步更新UI的四种方式
- JavaScript删除数组中指定元素