[連結串列】2.輸入一個連結串列,反轉連結串列後,輸出新連結串列的表頭。[多益,位元組考過]

ltcz99發表於2020-10-22

碼字不易,記得點贊加收藏

題目:輸入一個連結串列,反轉連結串列後,輸出新連結串列的表頭。

解答:例如:輸入1->5->6-->8->null,期待輸出8->6->5->1-null

1.定義一個ListNode pre = null; ListNode next = null; 定義一個前向節點指向null,一個後向節點指向空

2.

第一輪:

當前pre = null,next = null,head = 1

next = head..next (head = 1,next = 5)

head.next = pre (head.next = null)1->null

pre = head (pre = 1)

head = next (head = 5)

第二輪:

當前:pre = 1,next = 5,head 5

next = head..next (head = 5,next = 6)

head.next = pre (head.next = 1)5->1->null(此時的1就是head.next,所以指向只能這樣)

pre = head (pre = 5)

head = next (head = 6)

第三輪:

當前:pre = 5;next =6;head = 6;

next = head.next (head = 6,next = 8)

head.next = pre (head.next = 5)6->5->1->null(此時的5就是head.next,所以指向只能這樣)

pre = head (pre = 6)

head = next (head = 8)

第四輪:

當前:pre = 6;next =8;head = 8;

next = head.next (head = 8,next = null)

head.next = pre (head.next = 6)8->6>5->1->null(此時的6就是head.next,所以指向只能這樣)

pre = head (pre = 8)

head = next (head = null)此時結束迴圈,反向連結串列生成,返回頭結點pre

public class Solution {
    public ListNode ReverseList(ListNode head) {
        ListNode pre = null;
        ListNode next = null;
        while(head != null){
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }
}

 

相關文章