删除链表结点注意保证链表不会断开。删除的节点是尾结点时,并不能保证是O(1)时间。但平均下来时间复杂度仍然保持在O(1)。
public class List{ class Node{ int data; Node next; } int N; Node first; boolean isEmpty() { return first==null; }; int size() { return N; } public void insert(int val){ Node oldfirstNode=first; first=new Node(); first.data=val; first.next=oldfirstNode; N++; } public Node FindNodeByVal(int val){ Node pNode=first; while(pNode.data!=val){ pNode=pNode.next; } return pNode; } public Node FindPrev(Node target){ if(first==null || target==null) return null; Node pNode=first; while(pNode.next!=target){ pNode=pNode.next; } return pNode; } public void deleteNode(Node toBeDelete){ if( first==null || toBeDelete==null) return; //如果要删除的结点不是尾结点 if(toBeDelete.next!=null && first!=toBeDelete){ System.out.println("Delete node"); Node nextNode=toBeDelete.next; toBeDelete.data=nextNode.data; toBeDelete.next=nextNode.next; nextNode=null; } else if(first==toBeDelete){ System.out.println("Delete first node"); if(first.next==null) { first=null; } else first=first.next; toBeDelete=null; } //要删除的结点是尾结点 else{ System.out.println("Delete last node"); Node pNode=FindPrev(toBeDelete); pNode.next=null; toBeDelete=null; } } public void Print(){ Node pNode=first; while(pNode!=null){ System.out.print(pNode.data+" "); pNode=pNode.next; } System.out.println(); } public static void main(String[] args){ List list=new List(); for(int i=0;i<10;i++){ list.insert(i); } list.Print(); Node delNode1=list.FindNodeByVal(9); list.deleteNode(delNode1); list.Print(); Node delNode2=list.FindNodeByVal(3); list.deleteNode(delNode2); list.Print(); Node delNode3=list.FindNodeByVal(0); list.deleteNode(delNode3); list.Print(); } } /*output 9 8 7 6 5 4 3 2 1 0 Delete first node 8 7 6 5 4 3 2 1 0 Delete node 8 7 6 5 4 2 1 0 Delete last node 8 7 6 5 4 2 1 */
原文地址:http://blog.csdn.net/dutsoft/article/details/26722713