[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

Follow up:

A linked list can be reversed either iteratively or recursively. Could you implement both?

翻轉鏈表問題,簡單的非遞歸做法:

/**
 * 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) {
        if(head == NULL || head->next == NULL)
            return head;
        ListNode* pre = head;
        ListNode* p = head->next;
        ListNode* t;
        pre->next = NULL;
        while(p != NULL)
        {
            t = p->next;
            p->next = pre;
            pre = p;
            p = t;
        }
        return pre;
    }
};

 

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