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

LeetCode 19. Remove Nth Node From End of List--删除链表的倒数第n个结点

2017-08-25 00:54 716 查看
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.
class ListNode {
int val;
ListNode next;

ListNode(int x) {
val = x;
}
}

public class Main {
//方法一:遍历两遍
public ListNode removeNthFromEnd1(ListNode head, int n) {
int size = 0;
ListNode curNode = head;
while (curNode != null) {//获取链表长度
size++;
curNode = curNode.next;
}

if (size == 1 && n == 1) {
return null;
}

if (n == size) {
return head.next;
}

if (n > size) {
return null;
}
ListNode preNode = null;
preNode = head;
for (int i = 0; i < size - n - 1; i++) {
preNode = preNode.next;
}
preNode.next = preNode.next.next;
return head;
}

//方法二:遍历一遍,两个指针,一前一后,
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode start = new ListNode(0);//需要加一个头结点,比如1,2删除倒数第2个结点,需要把1删掉,此时1之前没有结点很难处理
start.next = head;
ListNode fastPoint = start;
ListNode slowPoint = start;

for (int i = 0; i < n + 1; i++) {//下标的关系:slowPoint+n+1 = fastPoint,比如1+2+1 = 4
fastPoint = fastPoint.next;
}
while (fastPoint != null) {//当fastPoint指向9时,还能继续下次next,
fastPoint = fastPoint.next;//此时fastPoint.next = null,slowPoint.next=7,然后才跳出循环
slowPoint = slowPoint.next;
}
slowPoint.next = slowPoint.next.next;//7->8->9变为7->9
//        return head;//不能再是返回head
return start.next;//slowPoint与start指向的是同一个地址,return slowPoint.next;也正确
}

public static void main(String[] args) {
ListNode node1 = new ListNode(1);
node1.next = new ListNode(2);
//        node1.next.next = new ListNode(3);
//        node1.next.next.next = new ListNode(4);
//        node1.next.next.next.next = new ListNode(5);
//        node1.next.next.next.next.next = new ListNode(6);
//        node1.next.next.next.next.next.next = new ListNode(7);
//        node1.next.next.next.next.next.next.next = new ListNode(8);
//        node1.next.next.next.next.next.next.next.next = new ListNode(9);
//        new Main().removeNthFromEnd(node1, 2);

System.out.println(new Main().removeNthFromEnd(node1, 2).val);//2
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐