反轉鏈表

題目描述:

定義一個函數,輸入一個鏈表的頭結點,反轉該鏈表並輸出反轉後鏈表的頭結點。

樣例

輸入:1->2->3->4->5->NULL

輸出:5->4->3->2->1->NULL

解法一:

不需要藉助輔助空間。

從第二個節點開始遍歷,每次取出一個節點,然後採用頭插法,插入到 head 後面就可以了。

/**
 * 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* first = head;
        ListNode* p = first->next;
        while(p)
        {
            first->next = first->next->next;
            p->next = head;
            head = p;
            p = first->next;
        }
        return head;
        
    }
};

 

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