剑指Offer(Java版)第十六题:给定单向链表的头指针和一个结点指针,定义一个函数在O(1)时间删除该结点。
/*
给定单向链表的头指针和一个结点指针,定义一个函数在O(1)时间删除该结点。
*/
public class Class16 {
static class ListNode{
int val;
ListNode next;
public ListNode(int value, ListNode nextNode){
val = value;
next = nextNode;
}
}
public ListNode deleteNode(ListNode headNode, ListNode deleteNode){
//判断链表是否为空
if(headNode == null || deleteNode == null){
return headNode;
}
//删除头节点
if(headNode == deleteNode){
headNode = null;
deleteNode = null;
//删除的节点是尾节点
}else{
if(deleteNode.next == null){
ListNode pointNode = headNode;
while(pointNode.next.next != null){
pointNode = pointNode.next;
}
pointNode.next = null;
}else{
deleteNode.val = deleteNode.next.val;
deleteNode.next = deleteNode.next.next;
}
}
return headNode;
}
public void test(ListNode head,ListNode PToBeDelete) {
System.out.println("============");
System.out.print("The original list is: ");
ListNode curr=head;
if(curr!=null) {
while(curr.next!=null) {
System.out.print(curr.val+",");
curr=curr.next;
}
System.out.println(curr.val);
}else {
System.out.println();
}
System.out.print("The node to be deleted is: ");
if(PToBeDelete!=null)
System.out.println(PToBeDelete.val);
else
System.out.println();
curr=deleteNode(head, PToBeDelete);
System.out.print("The result list is: ");
if(curr!=null) {
while(curr.next!=null) {
System.out.print(curr.val+",");
curr=curr.next;
}
System.out.println(curr.val);
}else {
System.out.println();
}
System.out.println("============");
}
public void test1() {
ListNode p4=new ListNode(4, null);
ListNode p3=new ListNode(3, p4);
ListNode p2=new ListNode(2, p3);
ListNode p1=new ListNode(1, p2);
test(p1, p2);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Class16 c = new Class16();
c.test1();
}
}