LeetCode:206. Reverse Linked List

一、問題描述

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

二、代碼實現

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        //pre永遠指向null,相當於一個尾節點
        ListNode* pre = NULL;
        ListNode* cur = head;
        while(cur != NULL){
            //next用來保存下一個節點。因爲會把當前節點cur拿下來,賦值給pre
            ListNode* next = cur->next;
            cur->next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
};

三、圖示

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章