C++创建链表及链表反转

直接上代码实现:

/*mylist.h*/
#pragma once

#include <iostream>
   
//链表节点
	struct ListNode
	{
		ListNode():iData(0),pNext(nullptr){}
		int iData;
		ListNode * pNext;
	};

	//带头结点链表
	class MyList
	{
	public:
		MyList() {};
		~MyList() {};

		//创建链表(尾插法)
		ListNode * creatList(int a[], int n);

		//打印链表
		void printList(ListNode * head);

		//链表反转
		ListNode * reverseList(ListNode * head);

	private:

	};


/*mylist.cpp*/
#include "stdafx.h"
#include "charFun.h"

ListNode * MyList::creatList(int a[], int n)
	{
		ListNode * pLastNode = new ListNode();//最后一个节点
		ListNode * head = pLastNode; //头结点

		ListNode * pNew;
		for (int i = 0; i < n; ++i)
		{
			pNew = new ListNode(); //新节点
			pNew->iData = a[i];
			pNew->pNext = nullptr;
			pLastNode->pNext = pNew;
			pLastNode = pNew;
		}
		return head;
	}

	void MyList::printList(ListNode *  head)
	{
		while (nullptr != head->pNext)
		{
			cout << head->pNext->iData << endl;
			head->pNext = head->pNext->pNext;
		}
	}

    /*链表反转是通过修改指针指向前一个节点实现*/
	ListNode *  MyList::reverseList(ListNode * head)
	{
		ListNode * pre = nullptr; //反转后头结点
		ListNode * pTem = nullptr;            
		while (nullptr != head->pNext)
		{
			pTem = pre;
			pre = head->pNext;
			head->pNext = head->pNext->pNext;
			pre->pNext = pTem;   //pre指向之前的节点 
		}

		//构建表头结点
		ListNode * pNewList = new ListNode();
		pNewList->pNext = pre;
		return pNewList;
	}


/*main*/
#include "stdafx.h"
#include <iostream>

using namespace std;

int main()
{
	int a[] = { 23, 12, 2, 0, 100, 34, 22, 45, 66, 99 ,233};
	MyList myList;
	ListNode * head;
	head = myList.creatList(a, sizeof(a)/sizeof(int));
	ListNode * head2 = myList.reverseList(head);
	myList.printList(head2);

	system("pause");
    
	return OK;
}

输出结果:

转载请注明出处:https://blog.youkuaiyun.com/youtiao_hulatang/article/details/104879204

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大锅菜~

谢谢鼓励~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值