欢迎加qq群:453398542 学习讨论,会定期分享资料课程,解答问题。
3、链表的基本操作
(1)采用尾插法建立一个链表;
(2)输入一个元素,在道表中查找该元素是否存在,请给出相关信息;
(3)将链表中的元素进行就地逆置。
#include<stdio.h>
#include<stdlib.h>
typedef struct Node{
int data;
struct Node *next;
}S;
S *search(S *head,int x,int n){
int i=0;
S *p=head;
while (p&&p->data!=x){
p=p->next;
i++;
}
if (i>=n){
printf("无此数\n");
}
else
{
printf("在第%d个节点\n",i+1);
}
return p;
}
S *reverse(S *head){
S *p=head->next;
head->next=NULL;
S *q,*s;
while (p){
q=p->next;
p->next=head;
head=p;
p=q;
}
return head;
}
void output(S *head){
S *p;
p=head;
while(p){
printf("%3d",p->data);
p=p->next;
}
}
int main(){
S *p,*head,*ps;
int i,n,x;
printf("输入个数:\n");
scanf("%d",&n);
head=ps=NULL;
printf("输入%d个数据:\n",n);
for(i=0;i<n;i++){
p=(S*)malloc(sizeof(S));
scanf("%d",&p->data);
if (i==0)
head=ps=p;
else
{
ps->next=p;
ps=p;
}
}
ps->next=NULL;
printf("输入要查找的数:\n");
scanf("%d",&x);
search(head,x,n);
head=reverse(head);
output(head);
return 0;
}