leetcode-206-reverse linked list

Problem Description:

Reverse a singly linked list.

题目大意:

反转一个单向链表

Solutions:

有许多方法可以反转一个单向链表,这里我们选择把每个结点都放在头结点之后一次,再从尾部连接头结点,最后再断环。

Code in C++:

/**
 * 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||!head->next) return head;
            ListNode * current = head->next;
            ListNode * next;
            while(current->next)
                {
                    next = current->next;
                    current->next=next->next;
                    next->next=head->next;
                    head->next=next;
                }
            current->next=head;
            ListNode *newhead=head->next;
            head->next=NULL;
            return newhead;   
        }
};