剑指offer_t15_反转链表

在这里插入图片描述
如题:

方法一:

直观思维,先可采用vector或者stack将该链表存下来,再新建一个头节点,再从容器中依次取出每个节点构成新链表,最后返回表头即可,注意vector需要反转一下。
采用vector:

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        if(!pHead) return nullptr;
        vector<ListNode*> v;
        while(pHead)
        {
            v.push_back(pHead);
            pHead = pHead->next;
        }
        reverse(v.begin(),v.end());
        ListNode *New_head = v[0];
        ListNode *p = New_head;
        for(int i=0;i<v.size();i++)
        {
            p->next = v[i];
            p=p->next;
        }
        p->next = nullptr;
        return New_head;
    }
};

采用stack:

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        if(!pHead) return nullptr;
        stack<ListNode*> s;
        while(pHead)
        {
            s.push(pHead);
            pHead = pHead->next;
        }
        
        ListNode *New_head = s.top();
        ListNode *p = New_head;
        while(!s.empty())
        {
            p->next = s.top();
            s.pop();
            p=p->next;
        }
        p->next = nullptr;
        return New_head;
    }
};

方法二:

迭代,
具体可参考:Leetcode刷题 206.反转链表 Reverse Linked List
这里核心就在于在反转一个节点时,需要用一个变量来存储当前节点的后驱,不然我们在反转时,把当前节点的next指针指向其前驱时,会导致当前节点的后驱丢失。

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        if(!pHead) return nullptr;
        if(!(pHead->next)) return pHead;
        ListNode *pre = NULL;
        ListNode *cur = pHead;
        ListNode *next = pHead;
        while(cur)
        {
            next = cur->next;
            cur->next = pre;
            pre = cur;
            cur = next;
        }
        return pre;

    }
};

方法三:

递归;

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

通信仿真爱好者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值