#include <iostream>
using namespace std;
struct node{
int val;
node * next;
};
struct node * init()
{// 构造一个空链表
struct node *head;
head=new node;
head->next=NULL;
return head;
}
void creat(struct node *head,int n){
struct node *p,*q;
p=head;
int t;
for(int i=0;i<n;i++){
q=new node;
cin>>t;
q->val=t;
p->next=q;
p=q;
};
p->next=NULL;
}
void printnode(struct node *head){
struct node *p;
p=head->next;
while(p){
cout<<p->val<<' ';
p=p->next;
}
}
struct node * deleteNode(struct node *head,int x){
if(head==NULL) return NULL;
struct node *p=head;
struct node *q=head->next;
while(q->val!=x ){
p=q;
q=q->next;
//如果x没有找到
if(q==NULL) break;
}
if (q!=NULL) {
p->next=q->next;
return head;
}
else return head;
}
struct node * insertNode(struct node *head,int x){
if (head==NULL) return NULL;
struct node * p=head;
struct node * q=head->next;
struct node * newNode=new node;
newNode->val=x;
while(q->val<x){
p=q;
q=q->next;
if(q==NULL) break;
}
p->next=newNode;
newNode->next=q;
return head;
}
struct node * moveFromLast(struct node *head){
struct node *p,*q;
if(head==NULL || head->next==NULL) return NULL;
p=head;
q=head->next;
while(q->next){
p=q;
q=q->next;
}
p->next=NULL;
q->next=head->next;
head->next=q;
return head;
}
int main(){
int n;
cin>>n;
// n=5;
struct node *head;
head=init();
creat(head,n);
printnode(head);
cout<<endl;
head=moveFromLast(head);
printnode(head);
cout<<endl;
head=deleteNode(head,4);
printnode(head);
cout<<endl;
head=insertNode(head,7);
printnode(head);
cout<<endl;
return 0;
}
链表的增删改
最新推荐文章于 2024-11-02 13:05:10 发布