标签:
1 /** 2 * 在O(1)的时间删除链表的节点 3 * 4 * @author 5 * 6 */ 7 public class Solution { 8 9 public static void deleteNode(Node head, Node deletedNode) { 10 if (null == head || null == deletedNode) { 11 return; 12 } 13 14 if (deletedNode.next != null) { // 删除的不是尾节点 15 16 System.out.println("1-----"); 17 18 Node nextNode = deletedNode.next; 19 deletedNode.value = nextNode.value; 20 deletedNode.next = nextNode.next; 21 22 } else if (head == deletedNode) { // 删除的是尾节点,同时尾节点也是头节点,整个链表只有一个节点 23 24 System.out.println("2-----"); 25 26 head = null; 27 deletedNode = null; 28 29 } else { // 删除的是尾节点,但是链表不止一个节点 30 31 System.out.println("3-----"); 32 33 // 遍历链表,找出尾节点的前一个节点,将next置为null 34 Node pNode = head; 35 while (pNode.next != deletedNode) { 36 pNode = pNode.next; 37 } 38 39 pNode.next = null; 40 deletedNode = null; 41 } 42 } 43 44 public static void main(String[] argss) { 45 46 Node third = new Node(2, null); 47 Node second = new Node(1, third); 48 Node first = new Node(0, second); 49 50 deleteNode(first, third); 51 52 } 53 } 54 55 class Node { 56 57 int value; 58 Node next; 59 60 public Node(int value, Node next) { 61 this.value = value; 62 this.next = next; 63 } 64 65 }
标签:
原文地址:http://www.cnblogs.com/jiangyi-uestc/p/5877643.html