P13在O(1)时间内删除链表结点


package
offer; //在 O(1)时间删除链表结点 public class Problem13 { public static void main(String[] args) { ListNode node1 = new ListNode(); ListNode node2 = new ListNode(); ListNode node3 = new ListNode(); ListNode node4 = new ListNode(); node1.nextNode = node2; node2.nextNode = node3; node3.nextNode = node4; node1.value = 1; node2.value = 2; node3.value = 3; node4.value = 4; System.out.println(node1.value); System.out.println(node2.value); System.out.println(node3.value); System.out.println(node4.value); //deleteNode(node1, node3); //deleteNode(node1, node1); //deleteNode(node1, node2); //deleteNode(node1, node4); deleteNode(node1, null); System.out.println(node1.value); System.out.println(node1.nextNode.value); System.out.println(node1.nextNode.nextNode.value); //System.out.println(node4.value); } public static void deleteNode(ListNode head,ListNode deleteNode){ if(head == null || deleteNode == null)return; if(deleteNode == head && head.nextNode == null)//delete head { head = null; }else { if(deleteNode.nextNode == null) {//delete tail,traverse loop ListNode temp = head; while(temp.nextNode.nextNode != null) { temp = temp.nextNode; } temp.nextNode = null; } else { deleteNode.value = deleteNode.nextNode.value; deleteNode.nextNode = deleteNode.nextNode.nextNode; } } } }

不用全部遍历链表,对比,删除;

把deleteNode的下一个结点复制到deleteNode的位置,覆盖deleteNode(实际上是删除deleteNode的下一个结点)

注意考虑用例:

结点只有一个的链表;

删除有多个结点的链表尾结点(遍历);

删除空结点,链表为空;

删除有多个结点的链表的中间一个结点。

posted @ 2016-08-22 10:48  sunshinelym  阅读(132)  评论(0编辑  收藏  举报