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

LeetCode Delete Node in a Linked List

2015-07-15 18:02 369 查看
Description:

Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.

Supposed the linked list is
1 -> 2 -> 3 -> 4
and you are given the third node
with value
3
, the linked list should become
1
-> 2 -> 4
after calling your function.
Solution:

既然这里直接给的是需要去掉的node,前一个node的next指针无法得到,所以这里不能用修改指针的方法;可以用直接修改值的方法。

需要注意的一个细节,next=temp.next;在最后设置next为tail的时候,一定要用temp.next=null;而不能是next=null。因为前者仅仅是修改了next指针指向的内容,temp.next还是指向原来的内存空间。

import java.util.*;

public class Solution {

public void deleteNode(ListNode node) {
ListNode temp = node, next;

while (temp != null) {
next = temp.next;
if (next != null) {
temp.val = next.val;
if (next.next == null) {
System.out.println(next.val + "  end");
temp.next = null;
break;
}
}

temp = next;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: