天天看點

lintcode--翻轉連結清單

翻轉一個連結清單

您在真實的面試中是否遇到過這個題?  Yes 樣例

給出一個連結清單1->2->3->null,這個翻轉後的連結清單為3->2->1->null

public class Solution {

    public ListNode reverse(ListNode head) {

        // write your code here

        ListNode  pre = null;

        ListNode temp = null;

        while(head!=null){

            temp = head.next;//儲存下一節點

            head.next = pre;

            //向後移動

            pre = head;

            head = temp;//下一個

        }

        //傳回前指針;

        return pre;

    }

}