链表的反转

               

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

class ListNode
{
public:

	int data; //数据域
	ListNode* next; //指针域

	ListNode(int x):data(x),next(NULL){}	
};

//输入处理
vector<int> inputV()
{
	int n;
	cout << "请输入链表元素的个数" << endl;
	cin >> n;
	vector<int> nums;
	

	cout << "请输入" << n << "个数";
	cout << endl;
	for (int i = 0; i<n; i++)
	{
		int temp;
		cin >> temp;
		nums.push_back(temp);
	}
	return nums;
}


//创建链表
ListNode* creat(vector<int>& nums)
{
	//创建头节点
	ListNode* head = NULL;
	head = new ListNode(0);

	ListNode* p = head; //记录头指针
	for (auto it: nums.end())
	{
		ListNode* pNewNode = new ListNode(*it);//创建新结点
		p->next = pNewNode; //上个节点指针域放新节点的地址

		p = pNewNode;//更新结点
	}
	return head;

}


//链表反转   head -> 1 -> 2 -> 3 -> 4 -> 5 ->NULL
//          NULL <- 1 -> 2 -> 3 -> 4 -> 5 ->NULL
//          NULL <- 1 <- 2 -> 3 -> 4 -> 5 ->NULL       
ListNode* reverseList(ListNode* head)
{	
	ListNode* pre = NULL; 
	ListNode* p = head;
	while (p)
	{
		ListNode* next = p->next; //记录下一个结点
		p->next = pre;
		pre = p;
		p = next;
	}
	return pre;
}

//打印链表
void printLi(ListNode* L) //传入头指针,利用头指针可找到整个链表
{	
	while (L->next !=NULL)
	{		
		
		cout << L->data << " ";
		L = L->next;
		
	}
	cout << endl;
}


int main()
{
	vector<int> nums;
	nums = inputV(); //inputNum()用户输入一组数字,保存在vector中	


	ListNode* head = NULL;
	head = creat(nums);	
	head = reverseList(head);
	printLi(head);

	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值