美文网首页
Linked List - Reverse Linked Lis

Linked List - Reverse Linked Lis

作者: 衣忌破 | 来源:发表于2017-04-26 10:48 被阅读2次

https://leetcode.com/problems/reverse-linked-list/#/solutions

题目很简单就是“反转”链表:
我的解法思路很简单,将所有节点的next指针指向前一个节点就可以了

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

但这题还有一种巧妙的做法就是利用递归

class Solution {
public:   
    ListNode* reverseList(ListNode* head) {
        if (!head || !(head -> next)) return head;
        ListNode* node = reverseList(head -> next);
        head -> next -> next = head;
        head -> next = NULL;
        return node; 
    }
}; 

相关文章

网友评论

      本文标题:Linked List - Reverse Linked Lis

      本文链接:https://www.haomeiwen.com/subject/gbkizttx.html