反轉鏈表


輸入一個鏈表,反轉鏈表後,輸出新鏈表的表頭java


解法一

提及反轉,第一個想到的確定是利用棧先進後出的特性。這道題固然能夠用棧來實現,可是對於註釋中那一塊不是很明白,先放着,若是有大佬知道的話求解答node

public class Solution {
	public ListNode ReverseList(ListNode head) {
		if (head == null)
			return null;
		
		Stack<ListNode> stack = new Stack<ListNode>();
		ListNode temp = head;
		do {
			stack.push(temp);
			temp = temp.next;
		} while (temp != null);
		//若是這裏的頭結點的next要不置爲空,就會致使遍歷時無限循環
		head.next = null;
	
		ListNode root = stack.pop();
		ListNode node = root;
		while (!stack.isEmpty()) {
			node.next = stack.pop();
			node = node.next;
		}
		return root;
	}
}

解法二

最好的辦法就是利用雙指針的方式指針

public class Solution {
    public ListNode ReverseList(ListNode head) {
        if(head == null)
            return null;
        // head爲當前節點,若是當前節點爲空的話,那就什麼也不作,直接返回null;
        ListNode pre = null;
        ListNode next = null;
        // 當前節點是head,pre爲當前節點的前一節點,next爲當前節點的下一節點
        // 須要pre和next的目的是讓當前節點從pre->head->next1->next2變成pre<-head next1->next2
        // 即pre讓節點能夠反轉所指方向,但反轉以後若是不用next節點保存next1節點的話,此單鏈表就此斷開了
        // 因此須要用到pre和next兩個節點
        // 1->2->3->4->5
        // 1<-2<-3 4->5
        while(head!=null){
            // 作循環,若是當前節點不爲空的話,始終執行此循環,此循環的目的就是讓當前節點從指向next到指向pre
            // 如此就能夠作到反轉鏈表的效果
            // 先用next保存head的下一個節點的信息,保證單鏈表不會由於失去head節點的原next節點而就此斷裂
            next = head.next;
            // 保存完next,就能夠讓head從指向next變成指向pre了,代碼以下
            head.next = pre;
            // head指向pre後,就繼續依次反轉下一個節點
            // 讓pre,head,next依次向後移動一個節點,繼續下一次的指針反轉
            pre = head;
            head = next;
        }
        // 若是head爲null的時候,pre就爲最後一個節點了,可是鏈表已經反轉完畢,pre就是反轉後鏈表的第一個節點
        // 直接輸出pre就是咱們想要獲得的反轉後的鏈表
        return pre;
    }
}
相關文章
相關標籤/搜索