首页 > 其他 > 详细

1.链表反转

时间:2021-05-30 20:01:44      阅读:13      评论:0      收藏:0      [点我收藏+]

 

struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};

方法1: 迭代

class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        ListNode *pre;
        ListNode *next;
        ListNode *curr;
        curr=pHead;
        pre=NULL;
        while(curr!=NULL)
        {
            next=curr->next;    //保存下一个
            curr->next=pre;    //指向前面一个
            pre=curr;          //保存前面一个
            curr=next;         //移动到下一个
        }
        return pre;
    }
};

方法2:递归

class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        if(pHead==NULL || pHead->next==NULL)
            return pHead;
        ListNode *new_head = ReverseList(pHead->next);
        pHead->next->next=pHead;
        pHead->next=NULL;
        return new_head;
    }
};

 

1.链表反转

原文:https://www.cnblogs.com/520dada/p/14828268.html

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