2-1 A - 数据结构实验之链表一:顺序建立链表
#include<stdio.h>
#include<string.h>
typedef struct Node//typedef使用后,下面的结构体可不用struct
{
int data;
struct Node *next;
}node;
node *creat(int n)
{
node *head,*p,*tail;
head=(node*)malloc(sizeof(node));//malloc函数,建立一个头节点;
head->next=NULL;//头节点指向空;
tail=head;//尾节点指向空;
for(int i=0;i<n;i++)
{
p=(node*)malloc(sizeof(node));//建立一个新的节点p;
scanf("%d",&p->data);//给节点p赋值;
p->next=NULL;//p指向空;
tail->next=p;//让tail指向p;
tail=p;//将p代替tail的位置进行循环,可以实现将新的p顺序加到链表中;
}//顺序建链表;
return head;
}
int main()
{
node *head,*p;
int n;
scanf("%d",&n);
head=creat(n);//顺序建链表;
p=head->next;//遍历链表;
while(p)//也可以写while(p!=NULL)
{
if(p->next==NULL)
printf("%d",p->data);
else printf("%d ",p->data);
p=p->next;
}//输出;
return 0;
}
2-2 B - 数据结构实验之链表二:逆序建立链表
#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
int data;
struct Node *next;
}node;
node *creat(int n)
{
node *head,*p;
head=(node*)malloc(sizeof(node));
head->next = NULL;//和顺序一样;
for(int i=0;i<n;i++)
{
p=(node*)malloc(sizeof(node));
scanf("%d",&p->data);
p->next=head->next;//让p指向head所指的;
head->next=p;//让head指向p,实现将p逆序建立链表。
}
return head;
}
int main()
{
int n;
scanf("%d",&n);
node *head,*p;
head=creat(n);
p=head->next;
while(p)
{
if(p->next==NULL)
printf("%d",p->data);
else printf("%d ",p->data);
p=p->next;
}
return 0;
}
2-3 C - 师--链表的结点插入
#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
int data;
struct Node *next;
}node;
void Insert(node *head,int m,int x)//执行插入操作的函数
{
node *q=(node *)malloc(sizeof(node)),*p=head;
q->data=x;//准备好新节点并赋值
for(int i=0;i<m&&p->next!=NULL;i++)//查找第m个,但如果p->next==NULL也要结束循环
{
p=p->next;//建立链表往后走
}
q->next=p->next;//将q插入找到的位置
p->next=q;
}
int main()
{
int n;
while(~scanf("%d",&n))
{
node *head,*p;
head=(node*)malloc(sizeof(node));
head->next&#