首页 > 其他 > 详细

LeetCode:反转链表

时间:2018-07-05 01:04:09      阅读:188      评论:0      收藏:0      [点我收藏+]

技术分享图片
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 == NULL) {
            cout << "The list is empty." << endl;
            return NULL;
        }   
        if (head->next == NULL) {
            return head;
        }
        ListNode* newHead = reverseList(head->next);
        head->next->next = head;
        head->next = NULL;
        return newHead;
    }
    
    // 迭代实现反转
    /*ListNode* reverseList(ListNode* head) {
        if (head == NULL) {
            cout << "The list is empty." << endl;
            return NULL;
        }   
        if (head->next == NULL) {
            return head;
        }
        ListNode* p = head;
        ListNode* pPrev = NULL;
        while (p != NULL) {
            ListNode* temp = p->next;
            p->next = pPrev;
            pPrev = p;
            p = temp;            
        } 
        return pPrev;
    }*/
};

LeetCode:反转链表

原文:https://www.cnblogs.com/yiluyisha/p/9266093.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!