#include<iostream>
#include<stdlib.h>
using namespace std;
struct ListNode{
int data;
ListNode *next;
};
void Insert(ListNode *head,int num);
void printL(ListNode *head);
void *change(ListNode* head);
void Clear(ListNode *head);
void Destory(ListNode *head);
void Insert(ListNode* head,int num)//实现插入排序
{
ListNode *p,*s;
p =head;
while(p->next&&num>p->next->data)
p = p->next;
s = new ListNode;
s->data = num;
s->next = p->next;//这里就插入了节点s
p->next = s;
}
void printL(ListNode* head)
{
ListNode* p = head->next;//打印时跳过头节点
while(p->next!=NULL){
cout<<p->data<<"->";
p=p->next;//p指向下一个节点
}
cout<<p->data;
cout<<endl;
}
void *change(ListNode *head)
{
ListNode *p,*q,*s;
p=head->next;
q=NULL;
head->next=NULL;//先把头指针拎出来
while(p!=NULL){
s=p->next;
p->next=q;//连接倒置的链表,一个个连
q=p;
p=s;
}
head->next=q;//因为p最后会指向NULL
return head;
}
void Clear(ListNode *head)
{
ListNode *p,*q;
p = head->next;
while (p){
q= p->next;
delete p;
p=q;
}
head ->next=NULL;
}
void Destory(ListNode *head)
{
Clear(head);
free(head);
}
int main()
{
ListNode *head =NULL;
head = new ListNode;//创建头节点;
head->data = 0;
head->next = NULL;
int n;
//cout<<"input n :"<<endl;
cin>>n;
//cout<<"please input n number"<<endl;
for(int i=0;i<n;i++){
int x;
cin>>x;
Insert(head,x);
}
// cout<<"output:"<<endl;
printL(head);
change( head);
printL(head);
Clear(head);
Destory(head);
return 0;
}
链表逆置
最新推荐文章于 2024-08-15 05:02:54 发布