#include<iostream>
using namespace std;
int n;
struct Node
{
Node* next;
int data;
};
void create(Node* head)
{
Node* p=head;
for(int i=n-1;i>=1;--i)
{
Node* newNode=new Node; //开辟新结点
newNode->data=i;
newNode->next=NULL; //记得每生成一个新结点,next=NULL
p->next=newNode;
p=p->next; //每次生成的新结点接在p后面
}
}
void print(Node* head)
{
Node* p=head;
while(p!=NULL)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
Node* reverse(Node* head)
{
Node* pNode=head;
Node* pNext=NULL;
Node* pPrev=NULL;
while(pNode!=NULL)
{
pNext=pNode->next;
pNode->next=pPrev; //反指,所以前面pPrev初始要为NULL
pPrev=pNode;
pNode=pNext;
}
return pPrev;
}
int main()
{
Node* head=new Node;
cout<<"Input n:";
cin>>n;
head->data=n;
head->next=NULL;
create(head);
cout<<"Generate a list:";
print(head);
head=reverse(head);
cout<<"After reversed:";
print(head);
//释放单链表
Node* p=NULL;
while(head!=NULL)
{
p=head;//保存本节点
head=head->next;// 找到下一个节点
delete(p);//释放本节点
}
return 0;
}
单链表翻转(小练习)
最新推荐文章于 2024-08-01 20:03:35 发布