LeetCode - E - Reverse Linked List

題意

Reverse a singly linked list.

click to show more hints.

Subscribe to see which companies asked this question.

解法

將當前元素插入到頭節點之前

實現

/**
 * 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* cur = head;
        while(cur->next != NULL){
            ListNode* next = cur->next;
            cur->next = next->next;
            next->next = head;
            head = next;
        }
        return head;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章