剑指offer 反转链表(C++)

题目描述

输入一个链表,反转链表后,输出新链表的表头。

思路1:

直观想法:采用堆栈进行反转(常用操作,先进后出嘛)

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        if(pHead == NULL || pHead->next == NULL) return pHead;
        std::stack res;
        ListNode* cur = pHead;
        ListNode* node;
        while(cur->next != NULL)
        {
            res.push(cur);
            cur = cur->next;
        }
        node = cur;
        while(!res.empty())
        {
            cur->next = res.top();
            res.pop();
            cur = cur->next;
        }
        cur->next = NULL;
        return node;
    }
};

思路2:

对链表进行遍历,记录前一指针pre(初始化为NULL),以及后一指针next。首先将下一指针保存到next,将pre赋值给当前指针的下一指针(指向前面),将当前指针赋值给pre,指针从next获取下一个指针的地址。

看代码比较容易理解

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

 

你可能感兴趣的:(剑指offer刷题)