首页 > 代码库 > Remove Nth Node From End of List
Remove Nth Node From End of List
地址:https://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/
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 值的合法性。最简单办法就是先遍历求得链表节点数目,然后删除指定结点,但是这样需要两次遍历链表。
public class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { if(head == null){ return null; } ListNode countList = head; int ListCount = 0; while(countList!=null){ ListCount++; countList = countList.next; } if(ListCount-n==0){ return head.next; } ListNode ans = head; int count = 0; ListNode pre = null; ListNode cur = null; while(head.next!=null){ count++; pre = head; cur = head.next; if(count == ListCount-n){ pre.next = cur.next; break; } head = head.next; } return ans; }}
有个方法可以只需要进行一次链表遍历,参见:http://blog.csdn.net/huruzun/article/details/22047381
public class Solution { public ListNode removeNthFromEnd(ListNode head, int n){ ListNode pre = null; ListNode ahead = head; ListNode behind = head; // ahead 节点先走n-1 步,behind 和ahead 一起走,当ahead到达最后一个节点,behind为需要删除元素 for(int i=0;i<n-1;i++){ if(ahead.next!=null){ ahead = ahead.next; }else { return null; } } while(ahead.next!=null){ pre = behind; behind = behind.next; ahead = ahead.next; } // 如果删除的是头结点 if(pre == null){ return behind.next; }else { pre.next = behind.next; } return head; }}
个人觉得第二种方法也没有什么太多优化,只是为了满足题目要求。但是这个方法联想到可以解决很多链表相关问题,比如求两个链表相交结点也可以通过这种类似这种路程关系解决。
Remove Nth Node From End of List
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。