链表--1-从尾到头打印链表-翻转链表

一、从尾到头打印链表

思路:

1、使用stack栈

        通常,这种情况下,我们不希望修改原链表的结构。返回一个反序的链表,这就是经典的“后进先出”,我们可以使用栈实现这种顺序。每经过一个结点的时候,把该结点放到一个栈中。当遍历完整个链表后,再从栈顶开始逐个输出结点的值,给一个新的链表结构,这样链表就实现了反转。

2、不用stack栈,使用reverse函数

#include <iostream>
#include <vector>
#include <stack>
using namespace std;

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

class Solution
{
public:
        //使用栈stack
         vector<int> printReverseLinklist(ListNode * head)
	{
		if (head == NULL)
			return vector<int>();
		
		stack<ListNode *> nodes;
		vector<int> result;
		ListNode * pNode = head;            //pnode指向头结点,然后指针在依次后移
		while (pNode != NULL)
		{
			nodes.push(pNode);            //节点依次入栈
			pNode = pNode->next;
		}
		while (!nodes.empty())
		{
			pNode = nodes.top();            //获取头结点,将值存在vector中
			result.push_back(pNode->val);
			nodes.pop();
		}
		return result;
	}
};

int main()
{
	Solution s;
	ListNode * head = new ListNode(2);
	ListNode * l1 = new ListNode(3);
	head->next = l1;
	ListNode * l2 = new ListNode(4);
	l1->next = l2;
	vector<int> result = s.printReverseLinklist(head);
	for (auto i : result)
		cout << i;
	cout << endl;
	system("pause");
	return 0;
}
class Solution
{
public:
        //不用stack,用vector的reverse函数
         vector<int> printReverseLinklist(ListNode * head)
	{
		if (head == NULL)
			return vector<int>();
		
		vector<int> result;
		ListNode *pnode = head;
		while (pnode != NULL)
		{
			result.push_back(pnode->val);
			pnode = pnode->next;
		}
		reverse(result.begin(), result.end());
		return result;
	}
};

二、翻转链表

思路:

        改变链表的结构,使用三个指针,分别指向当前遍历到的结点、它的前一个结点以及后一个结点。

在遍历的时候,做当前结点的尾结点和前一个结点的替换。


class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) 
    {
        if (pHead == nullptr)
            return nullptr;
        ListNode *pPre = nullptr;   //作为最终的尾巴,为nullptr
        ListNode *pCur = pHead;        
        ListNode *pNext = nullptr;
        while (pCur != nullptr)
        {
            pNext = pCur->next;
            pCur->next = pPre;
            if (pNext == nullptr)
                break;
            pPre = pCur;
            pCur = pNext; 
        }
        return pCur;
    }
};



猜你喜欢

转载自blog.csdn.net/ax_hacker/article/details/80959432