LeetCode 206. Reverse Linked List(C++版)

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

递归版本:

class Solution {
public: 
    ListNode * reverseListIter(ListNode * head, ListNode * newhead){
        if(head == NULL) return newhead;
        
        ListNode * nextnode = head -> next;
        head -> next = newhead;
        return reverseListIter(nextnode, head);
    }
    ListNode * reverseList(ListNode *head){
        return reverseListIter(head, NULL);
    }
};


你可能感兴趣的:(leetcode,反转单链表)