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

Remove Nth Node From End of List

2017-09-20 16:27 169 查看
原题:

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,去掉倒数第n个节点。

思考过程:

一开始没多想,直接就写,发现第一个问题是不知道链表长度,只好遍历一下求出长度。然后找到所要去掉的节点之前那个节点listnode1.listnode1.next = listnode1.next.next。当然为了返回这个链表,要在head节点之前加一个节点first,最后返回first.next。最开始没考虑只有一个节点的情况,才意识到要从first开始遍历而不是head,否则只有一个节点的情况没法处理。

结果代码:

public ListNode removeNthFromEnd(ListNode head, int n) {
int length = 0,count = 0;
ListNode listNode = head,first = new ListNode(0);
first.next = head;
while (listNode != null){
listNode = listNode.next;
length ++;
}
listNode = first;
while (count < length - n){
listNode = listNode.next;
count++;
}
listNode.next = listNode.next.next;
return first.next;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: