[leetcode] 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) {
        if(!head || !(head->next)) return head;
        ListNode* p=head->next;
        ListNode* ln=reverseList(head->next);
        p->next=head;
        head->next=NULL;
        return ln;
    }
};

之前错误:

 把p->next=head; 写成 ln->next=head;

ln是返回链表的头指针

 

你可能感兴趣的:([leetcode] 206. Reverse Linked List)