206. Reverse Linked List

来源:互联网 发布:普利茅斯大学知乎 编辑:程序博客网 时间:2024/06/08 19:46

Reverse a singly linked list.

/** * 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) {        ListNode* tmp = NULL;        ListNode* newHead = NULL;        if(head == NULL || head->next == NULL) return head;        while(1){            newHead = head->next;            head->next = tmp;            tmp = head;            if(newHead == NULL)                break;            head = newHead;        }        return head;    }};
0 0