首页 > 代码库 > Leetcode-206 Reverse Linked List

Leetcode-206 Reverse Linked List

#206.  Reverse Linked List

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* p=NULL;
        ListNode* q=head;
        while(q!=NULL)
        {
            ListNode *newlist=new ListNode(q->val);
            newlist->next=p;
            p=newlist;
            q=q->next;
        }
        return p;
    }
};

 

Leetcode-206 Reverse Linked List