您的位置:首页 > Web前端 > Node.js

【Leetcode】Remove Nth Node From End of List

2015-11-19 19:46 579 查看
题目链接:https://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.

思路:

1、先求链表长度,遍历链表找到要删除结点需要的指针,需要遍历两遍。

2、用两个指针,两指针距离为n,并且每次移动一步,直到表尾,此时前一个指针指向的就是倒数第n个结点

算法1:

public int getListLength(ListNode head) {
int length = 0;
ListNode p = head;
while (p != null) {
length++;
p = p.next;
}
return length;
}

public ListNode removeNthFromEnd(ListNode head, int n) {
int length = getListLength(head);
ListNode pre = null, p = head;
int i = length - n + 1;// 正序移动距离
while (--i > 0) {// 获取要删除节点的指针
pre = p;
p = p.next;
}
if (pre != null) {
pre.next = p.next;
} else {
head = p.next;// 当删除头节点时
}
return head;
}


算法2:

public ListNode removeNthFromEnd(ListNode head, int n) {
// nth指向p前n个结点,pre为nth前一个结点,即pre/nth/p
ListNode p = head, nth = head, pre = null;
while (--n > 0) {
p = p.next;
}
while (p.next != null) {
p = p.next;
pre = nth;
nth = nth.next;
}
// 此时p指向表尾,nth指向倒数n个结点
if(pre==null){ //如果删除的是头结点
head = nth.next;
}else{
pre.next = nth.next;
}
return head;
}


算法3:

考虑上面的算法需要考虑到如果删除的是表头,需要单独处理,经常在别人的题解中见到头结点可以将表头当普通结点一样操作,简化程序。

下面的代码就是加了头结点。

public ListNode removeNthFromEnd(ListNode head, int n) {
// nth指向p前n个结点,pre为nth前一个结点,即pre/nth/p
ListNode newHead = new ListNode(0);// 头结点
ListNode p = head, nth = head, pre = newHead;
newHead.next = head;
while (--n > 0) {
p = p.next;
}
while (p.next != null) {
p = p.next;
pre = nth;
nth = nth.next;
}
// 此时p指向表尾,nth指向倒数n个结点
pre.next = nth.next;
return newHead.next;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: