#include<iostream>
#include<cassert>
using namespace std;
typedef struct Node
{
int value;
Node* pNext;
}Node,*pNode;
//创建链表
Node * creat()
{
int numberOfNode=5;
int data;
pNode head=new Node;
if(head==NULL)
cout<<"分配内存失败\n";
head->pNext=NULL;
pNode p=head;
pNode q=NULL;
while(numberOfNode--)
{
q=new Node;
assert(1!=NULL);
cin>>data;
q->value=data;
p->pNext=q;
p=q;
}
p->pNext=NULL;
return head;
}
//实现链表逆序
pNode reverseList(pNode head)
{
//空链表或者只有一个节点
if(head==NULL || head->pNext==NULL)
return head;
//pre,curr分别指向首节点,第二个节点
pNode pre=head->pNext;
pNode curr=pre->pNext;
pre->pNext=NULL;
pNode next=NULL;
while(curr!=NULL)
{
next=curr->pNext;
curr->pNext=pre;
pre=curr;
curr=next;
}
head->pNext=pre;//有头节点的链表
}
//打印链表
void printList(pNode head)
{
pNode start=head->pNext;
while(start!=NULL)
{
cout<<start->value<<" ";
start=start->pNext;
}
}
int main()
{
pNode p1=creat();
printList(p1);
cout<<endl;
printList(reverseList(p1));
return 0;
}
链表逆序
最新推荐文章于 2023-04-02 17:44:37 发布