C++ linked list creation and output in reverse order

C++ linked list creation operation

#include <iostream>
#include <vector>

using namespace std;

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

vector<int> printListFromTailToHead(ListNode* head) {
    
    
	vector<int> ref;
	ListNode* p = head;
	while (p != NULL)
	{
    
    
		ref.insert(ref.begin(), p->val);
		p = p->next;
	}
	return ref;
}

void createNode(ListNode* pHead, vector<int> inputArray)
{
    
    
	ListNode* p = pHead;
	for (size_t i = 0; i < inputArray.size(); i++)
	{
    
    
		ListNode* pNewNode = NULL;
		pNewNode = new ListNode(inputArray[i]);
		
		p->next = pNewNode;
		p = pNewNode;
	}
}

int main()
{
    
    
	//链表元素数据
	vector<int> InputArray = {
    
     67, 0, 24, 58, 33, 25 };
	
	//创建表头: 新建表头+开辟空间
	ListNode* head = NULL;
	head = new ListNode(0);
	
	//创建链表
	createNode(head, InputArray);
	
	//倒序输出
	vector<int> outRef = printListFromTailToHead(head->next);
	
	system("pause");
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_38337524/article/details/110241177