在o(1)时间删除链表节点
剑指offer 面试题13 : 在o(1)时间删除链表节点
给定单向链表的头指针和一个节点指针,定义一个函数在o(1)时间删除该节点。
代码如下:
这里先使用数组创建一个链表(头插法和尾插法都有),然后需要创建一个节点,该节点在链表中的位置是未知的,故还需要创建一个搜索该节点在链表中的位置的函数,具体代码如下:
代码
/**
*
*/
package problem2;
/**
* @author Hutongling
*
*/
class Node {
int value;
Node next=null;
public Node(){}
public Node(int value){
this.value=value;
}
public Node(int value,Node next){
this.value=value;
this.next=next;
}
public void setValue(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public Node getNext() {
return next;
}
}
public class 在o1时间删除链表节点 {
public Node deleteNodeIn1(Node head, Node node) {
Node tempHead=head; //保留头结点用来后面的返回
if (head == null || node == null) // 当头结点或者删除节点为null的时候无法进行删除
return null;
else if (node == head) { // 当Node节点就是头街点的时候,删除头结点
head = null;
} else {
while (head.next != null) // 当删除的节点是尾节点的时候,遍历到最后删除尾节点
head = head.next;
if (head == node) {
head.next = node.next;
node = null;
}
else if(head!=node){
Node temp=node.next;
node.value=node.next.value;
node.next=node.next.next;
temp=null;
}
}
return tempHead;
}
//使用头插法建立链表
public Node createListUseHeadInsert(int[] data){
if(data==null || data.length==0)
return null;
Node head=new Node(data[0]);
for(int i=1;i<data.length;i++){
Node node=new Node(data[i]);
node.next=head;
head=node;
}
return head;
}
//使用尾插法建立链表
public Node createListUseTailInsert(int[] data){
if(data==null || data.length==0)
return null;
Node tail=new Node(data[0]); //建立一个尾节点
Node head=tail; //建立一个指向尾节点的头节点用于返回
for(int i=1;i<data.length;i++){
Node node=new Node(data[i]); //新建一个节点
tail.next=node; // 将该新建的节点插入到尾节点后面
tail=node; //将尾节点指向刚刚插入的节点
}
return head;
}
//遍历链表
public void readList(Node head){
if(head==null)
return;
while(head.next!=null){
System.out.print(head.value + " ");
head=head.next;
}
System.out.println(head.value);
}
public Node searchNode(Node head,Node node){
if(head==null || node==null)
return null;
else while(head.next!=null){
if(node.getValue()==head.getValue())
return head;
head=head.next;
}
return head;
}
public static void main(String[] args) {
在o1时间删除链表节点 test=new 在o1时间删除链表节点();
int data[]={1,2,3,4,5,6,7,8,9,10,11,12,14,14,15,27};
Node listHeadInsert=test.createListUseHeadInsert(data);
Node listTailInsert=test.createListUseTailInsert(data);
System.out.println("使用头插法建立的链表:");
test.readList(listHeadInsert);
System.out.println("使用尾插法建立的链表:");
test.readList(listTailInsert);
Node nodeHeadInsert=test.searchNode(listHeadInsert,new Node(11));
Node nodeTailInsert=test.searchNode(listTailInsert,new Node(14));
System.out.println("使用头插法之后删除元素之后打印链表:");
test.readList(test.deleteNodeIn1(listHeadInsert, nodeHeadInsert));
System.out.println("使用尾插法之后删除元素之后打印链表:");
test.readList(test.deleteNodeIn1(listTailInsert, nodeTailInsert));
}
}
运行结果:
使用头插法建立的链表:
27 15 14 14 12 11 10 9 8 7 6 5 4 3 2 1
使用尾插法建立的链表:
1 2 3 4 5 6 7 8 9 10 11 12 14 14 15 27
使用头插法之后删除元素之后打印链表:
27 15 14 12 11 10 9 8 7 6 5 4 3 2 1
使用尾插法之后删除元素之后打印链表:
1 2 3 4 5 6 7 8 9 10 11 12 14 15 27