重學資料結構(四)——實現單鏈表的反轉
阿新 • • 發佈:2020-07-24
單鏈表反轉
思路:
單鏈表反轉:就是把每個節點的指標域由原來的指向下一個節點變為指向其前一個節點。 思路: 1.因為單鏈表沒有指向前一個節點的指標域,所以這裡需要建立一個指向前一個節點的指標pre,用於儲存每一個節點的前一個節點。 2.需要定義一個儲存當前節點的指標cur,以及下一個節點的next。 3.先建立cur(當前節點),pre(前一個節點)指標後,遍歷單鏈表,將當前節點的指標域指向前一個節點,之後將定義的pre和cur指標往後移動,直至遍歷到最後一個節點停止。
Node類的實現
package com.codezs.datastruct.mylinkedlist; public class Node<T> { T data; Node<T> next; Node(Node<T> next) { this.next = next; } public Node(T data, Node<T> next) { this.data = data; this.next = next; } public T getData(){ return data; } public Node<T> getNext(){ return next; } public void setNext(Node<T> next){this.next = next;}; }
package com.codezs.datastruct.mylinkedlist; public class LinkListReverse { //實現單鏈表的反轉 public static Node reverse(Node node){ //當前節點 Node cur = node; //前一個節點 Node pre = null; while (cur != null){ //取出當前節點的下一個節點 Node next = cur.next; //當前節點的next指向前一個節點 cur.next = pre; //前一個節點向後移動 pre = cur; //當前節點向後移動 cur = next; } return pre; } }