面试题18:删除链表的节点
题目要求:
在o(1)时间内删除单链表的节点。
解题思路:
直接删除单链表某一节点,无法在o(1)时间得到该节点的前一个节点,因此无法完成题目要求。可以将欲删节点的后一个节点的值拷贝到欲删节点之上,删除欲删节点的后一个节点,从而可以在o(1)时间内完成删除。(对于尾节点,删除仍然需要o(n),其他点为o(1),因此平均时间复杂度为o(1),满足要求)
package structure;
/**
* Created by ryder on 2017/6/13.
*/
public class ListNode<T> {
public T val;
public ListNode<T> next;
public ListNode(T val){
this.val = val;
this.next = null;
}
@Override
public String toString() {
StringBuilder ret = new StringBuilder();
ret.append("[");
for(ListNode cur = this;;cur=cur.next){
if(cur==null){
ret.deleteCharAt(ret.lastIndexOf(" "));
ret.deleteCharAt(ret.lastIndexOf(","));
break;
}
ret.append(cur.val);
ret.append(", ");
}
ret.append("]");
return ret.toString();
}
}
package chapter3;
import structure.ListNode;
/**
* Created by ryder on 2017/7/7.
* o(1)时间删除链表的节点
*/
public class P119_DeleteNodeInList {
public static ListNode<Integer> deleteNode(ListNode<Integer> head,ListNode<Integer> node){
if(node==head){
return head.next;
}
else if(node.next!=null){
node.val = node.next.val;
node.next = node.next.next;
return head;
}
else{
ListNode<Integer> temp=head;
while(temp.next!=node)
temp = temp.next;
temp.next = null;
return head;
}
}
public static void main(String[] args){
ListNode<Integer> head = new ListNode<>(1);
ListNode<Integer> node2 = new ListNode<>(2);
ListNode<Integer> node3 = new ListNode<>(3);
head.next = node2;
node2.next = node3;
System.out.println(head);
head = deleteNode(head,node3);
System.out.println(head);
head = deleteNode(head,head);
System.out.println(head);
}
}
运行结果
[1, 2, 3]
[1, 2]
[2]