#include<stdio.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node *next;
};
struct Node *create() //头插法,逆序构成链表
{
struct Node *head,*p;
head=NULL;
int x;
while(scanf("%d",&x)&&x!=-1)
{
p=(struct Node*)malloc(sizeof(struct Node));
p->data=x;
p->next=head;
head=p;
}
return head;
}
struct Node* create2()
{
struct Node* head,*p,*q; //尾插法,正序构成链表,q为辅助滚动指针,用于连接
int x;
while(scanf("%d",&x)&&x!=-1)
{
p=(struct Node*)malloc(sizeof(struct Node));
p->data=x;
p->next=NULL;
if(head==NULL)
{
head=q=p;
}
else{
q->next=p;
q=p;
}
}
return head;
}
void output(struct Node *head)
{
struct Node* p;
p=head;
while(p!=NULL)
{
printf("%d ",p->data);
p=p->next;
}
printf("\n");
}
struct Node* insert(struct Node* head,int x)
{
struct Node *p,*q;
p=(struct Node* )malloc(sizeof(struct Node));
p->data=x;
if(head==NULL||head->data>x) //头空或要插在头部
{
p->next=head;
head=p;
return head;
}
q=head;
while(q->next!=NULL &&q->next->data<x)
{
q=q->next; //q指针滚动
}
p->next=q->next;
q->next=p;
return head;
}
struct Node* del(struct Node* head,int x)
{
struct Node *p,*q;
if(head==NULL) return head; //空表无删
if(head->data==x) //删头,free
{
q=head;
head=head->next;
free(q);
return head;
}
p=head;
while(p->next!=NULL&&p->next->data!=x)
{
p=p->next;
}
if(p->next!=NULL) //如果有删的
{
q=p->next;
p->next=q->next;
free(q);
}
return head; //没有直接返回了
}
int main()
{
int x,y;
struct Node *head;
head=create();
output(head);
head=create2();
output(head);
head=insert(head,x);
output(head);
head=del(head,y);
output(head);
}
链表的一些基本操作
最新推荐文章于 2024-06-04 18:31:30 发布