java實現單鏈表的反轉

問題:一個單鏈表將其反轉

     單鏈表是一種常見的數據結構,對於鏈表中的每一個結點都包含兩部分:數據域和指針域。例如,有一個鏈表1—>2—>3—>4,反轉後爲4—>3—>2—>1。

解決:

1. 遍歷反轉法
2. 遞歸反轉法

定義鏈表結點的實體類

代碼:

public class Node {
	private Object data;//單鏈表結點的數據域
	private Node next;//單鏈表結點的指針域
	
	public Node(Object data){
		this.data = data;
	}
	public Node(Object data,Node next){
		this.data = data;
		this.next = next;
	}
	
	public Object getData() {
		return data;
	}
	public void setData(Object data) {
		this.data = data;
	}
	public Node getNext() {
		return next;
	}
	public void setNext(Node next) {
		this.next = next;
	}	
}

1.遍歷反轉法

代碼:

	//遍歷反轉法
	public static Node reverseListNode1(Node head){
		if(head==null || head.getNext()==null){
			return head;
		}
		Node preNode = null;//前一個結點的指針
		Node curNode = head;//當前結點的指針
		Node nextNode = null;//下一個結點的指針
		while(curNode!=null){
			nextNode = curNode.getNext();
			curNode.setNext(preNode);
			preNode = curNode;
			curNode = nextNode;
		}
		return preNode;
	}

分析(主要是分析while循環)

  1. 先用nextNode記住當前結點的下一個結點,即:nextNode = curNode.getNext();
  2. 將當前結點的指針域指向前驅結點,即:curNode.setNext(preNode);
  3. 前驅節點後移到當前結點,即:preNode = curNode;
  4. 當前結點後移到後繼結點,即:curNode = nextNode;

2.遞歸反轉法

代碼:

	//遞歸法反轉鏈表
	public static Node reverseListNode2(Node head){
		if(head==null || head.getNext()==null){
			return head;
		}
		Node nextNode = head.getNext();//獲取當前結點head的下一個結點nextNode
		Node newHead = reverseListNode2(nextNode);
		nextNode.setNext(head);//將當前結點nextNode的指針域指向前驅結點head
		head.setNext(null);
		return newHead;
	}

分析:
    遞歸操作就是一個先遞後歸的過程,不斷調用reverseListNode2(nextNode)不斷向下傳遞就是爲了獲取新的頭結點(即原鏈表的尾結點);向上歸的過程每個結點將自己的指針域設置成前驅結點,即:nextNode.setNext(head),head.setNext(null)就是爲了將原有的頭結點,即反轉後的尾結點的指針域指向null。雖然在每次歸的過程中都會執行head.setNext(null);但第2次歸會將第1次的覆蓋,第3次會將第2次的覆蓋掉,直到反轉後的鏈表的尾部結點,尾部結點指向null。
測試代碼:

	public static void main(String[] args) {
		
		Node node1 = new Node(1);
		Node node2 = new Node(2);
		Node node3 = new Node(3);
		Node node4 = new Node(4);
		
		node1.setNext(node2);
		node2.setNext(node3);
		node3.setNext(node4);
		
		Node h = node1;
		while(h!=null){
			System.out.print(h.getData()+" ");
			h = h.getNext();
		}
		System.out.println();
		System.out.println("=============================");
		Node head = reverseListNode1(node1);
		while(head!=null){
			System.out.print(head.getData()+" ");
			head = head.getNext();
		}
		
	}

結果:
在這裏插入圖片描述
轉載出處:

  1. https://blog.csdn.net/lwkrsa/article/details/82015364
  2. https://blog.csdn.net/qq_32534441/article/details/91872381
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章