C++ reverse linked list complete code

#include<iostream>

using namespace std;

struct ListNode
{
    
    
	int val;
	ListNode* next;
};

//反转链表
ListNode* reverseList(ListNode* pHead)
{
    
    
	if (!pHead || !pHead->next)
		return pHead;
	ListNode* tail = reverseList(pHead->next);
	pHead->next->next = pHead;
	pHead->next = NULL;
	return tail;
}

//打印链表
void printList(ListNode* head)
{
    
    
	while (head)
	{
    
    
		cout << head->val;
		head = head->next;
		if (head)
			cout << "->";
	}
	cout << endl;
}

	int main()
	{
    
    
		//创建链表
		ListNode* head = NULL;
		ListNode* cur = NULL;
		for (int i = 1; i <= 5; ++i)
		{
    
    
			ListNode* node = new ListNode;
			node->val = i;
			node->next = NULL;
			if (head == NULL)
			{
    
    
				head = node;
				cur = node;
			}
			else
			{
    
    
				cur->next = node;
				cur = node;
			}
		}
		printList(head);
		printList(reverseList(head));
		return 0;
	}

Guess you like

Origin blog.csdn.net/qq_43729554/article/details/108558512