單向鏈表,單向循環鏈表的基本操作

鏈表可以解決數組對存儲空間要求的問題,可以充分的利用存儲空間,可以根據實際使用的需要來使用內存,鏈表的插入節點和刪除節點都數組要簡單,因爲只要用指針加以處理就行了 ,但是在數組的查找上,數組的速度比鏈表快,因爲從數組的索引就可以找到想要的數據,而鏈表需要花費很多時間去比較每一個節點,才能找到自己想要數據。

單向鏈表的每一個節點的數據結構都可以分爲兩個域,一個數據域,一個是指針域,因此可以以此來構建一個節點類

public class NodeType {

	public int data; //存放節點的數據
	
	public NodeType next; //存放下一個節點的引用
	
	public NodeType(int data){
		this.data = data;
	}

	public NodeType(){
		
	}
}

下面的代碼實現了獲取所有的鏈表節點,增加,刪除和鏈表的反轉

public class Test {

	public  void add(NodeType head,NodeType node){
		NodeType prev = null;
		NodeType current = head.next;
		while( current != null && current.data < node.data){
			prev = current;
			current = current.next;
		}
	
		prev.next = node;
		node.next = current;
	}
	
	/**
	 * 
	 * @param head
	 * @param node 要被刪除的節點
	 */
	public void romving(NodeType head,NodeType node){
		NodeType current = head.next;
		NodeType prev =  null;
		while(current != null && current.data != node.data){
				prev = current;
				current = current.next;
		}
		
		if(current == null){
			System.out.println("您輸入的節點不存在");
		}else{
			prev.next = current.next;
			current = null;
		}
	}
	
	
	/**
	 * 
	 * @param head
	 * @return 鏈表的長度
	 */
	public int getlength(NodeType head){
		NodeType current = head.next;
		int length = 0;
		while(current != null){
			length ++;
			current = current.next;
		}
		return length;
	}
	
	
	/**
	 * 
	 * @param head
	 * 獲取所有的節點
	 */
	public void getAllNode(NodeType head){
		NodeType current = head.next;
		while(current != null){
			System.out.print(" ");
			System.out.print(current.data);
			current = current.next;
		}
	}
	
	public NodeType invert(NodeType head){
		NodeType forward = head.next;
		NodeType current = null;
		NodeType prev = null;
		
		while(forward != null){
			prev = current;
			current = forward;
			forward = forward.next;
			current.next = prev;
		}
		return current;
	}
	/**
	 * 
	 * 測試鏈表的長度,鏈表的反轉,鏈表的刪除和增加
	 */
	
	public static void main(String args[]){
		NodeType head = new NodeType();
		NodeType a = new NodeType(55);
		NodeType b = new NodeType(64);
		NodeType c = new NodeType(78);
		NodeType d = new NodeType(85);
		NodeType e = new NodeType(98);
		NodeType f = new NodeType(112);
		
		head.next = a;
		a.next = b;
		b.next = c;
		c.next = d;
		d.next = e;
		e.next = f;		
		
		Test test = new Test();
		test.add(head, new NodeType(95));
		test.getAllNode(head);
		test.romving(head, e);
		test.getAllNode(head);
		System.out.println(test.getlength(head));
		
		
	
		
		NodeType newHead = test.invert(head);
		System.out.println(newHead.data + "*");
		test.getAllNode(newHead);
	}
	
}


1.鏈表的插入 假設需要在prev節點和current節點之間插入節點node ,只需要將prev.next = node ; node.next = current即可

2.鏈接的刪除,需要刪除節點prev的後一個節點current,那麼只要將prev.next = current.next; current = null即可./

3.獲取鏈表的長度,需要注意的是,while循環之中,是current != null 而不是 current.next != null,這兩個的區別需要弄清楚。

4.鏈表的反轉,需要藉助三個節點,prev ,current ,forward,那麼每一次循環實現,current 節點指向其前一個節點prev ,直到current 節點是最後一個節點。





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章