直接上代码实现:
/*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