1.创建带头节点的链表,并且遍历输出。
题目
#include <stdio.h>
#include <stdlib.h>
#define N 8
typedef struct list
{ int data;
struct list *next;
} SLIST;
SLIST *creatlist(int *a)
{
SLIST *h,*p,*q;
int i;
h = p = (SLIST *)malloc(sizeof(SLIST));
for(i = 0; i < N; i++) {
q = (SLIST *)malloc(sizeof(SLIST));
q->data = a[i];
p->next = q;
p = q;
}
p->next = 0;
return h;
}
void outlist(SLIST *h)
{
SLIST *p = h->next;
while(p) {
printf("%d ",p->data);
p = p->next;
}
printf("\n");
}
int main(void)
{
SLIST *head;
int a[N],i;
for(i=0;i<N;i++)
{
scanf("%d",&a[i]);
}
head=creatlist(a);
outlist(head);
return 0;
}
2.插入新链表,保持顺序,并遍历输出链表。
#include <stdio.h>
#include <stdlib.h>
typedef struct list
{ int data;
struct list *next;
} SLIST;
SLIST *creatlist()
{
SLIST *head,*tail,*cnew;
int num;
head=NULL;
while(1)
{
scanf("%d",&num);
if(num==-1)
break;
cnew=(SLIST*)malloc(sizeof(SLIST));
cnew->data=num;
cnew->next=NULL;
if(head==NULL)
head=cnew;
else
tail->next=cnew;
tail=cnew;
}
return head;
}
void outlist(SLIST *h)
{
SLIST *p;
for(p=h;p!=NULL;p=p->next)
printf("%d ",p->data);
printf("\n");
}
int main(void)
{
SLIST *head;
head=creatlist();
outlist(head);
return 0;
}
3.插入新的链表,并遍历输出。
#include <stdio.h>
#include <stdlib.h>
#define N 8
typedef struct list
{ int data;
struct list *next;
} SLIST;
SLIST *insertlist(SLIST * p,int *pvalue)
{
SLIST *tmp=p,*tmp_p;
int t=*pvalue;
while(tmp->next!=NULL&&tmp->next->data<t)
tmp=tmp->next;
tmp_p=(SLIST *)malloc(sizeof(SLIST));
tmp_p->next=tmp->next;
tmp_p->data=t;
tmp->next=tmp_p;
return p;
}
SLIST *creatlist(int *a)
{
SLIST *h,*p,*q; int i;
h=p=(SLIST *)malloc(sizeof(SLIST));
for(i=0; i<N; i++)
{ q=(SLIST *)malloc(sizeof(SLIST));
q->data=a[i];
p->next=q;
p=q;
}
p->next=0;
return h;
}
void outlist(SLIST *h)
{
SLIST *tmp =h->next;
while(tmp!=NULL){
printf("%d ",tmp->data);
tmp=tmp->next;
}
}
int main(void)
{
SLIST *head;
int a[N];
int nvalue,i;
for(i=0;i<N;i++)
{
scanf("%d",&a[i]);
}
scanf("%d",&nvalue);//插入的结点数据
head=creatlist(a);
head=insertlist(head,&nvalue);
outlist(head);
return 0;
}
4.删除指定节点,并遍历输出。
#include <stdio.h>
#include <stdlib.h>
#define N 8
typedef struct list
{ int data;
struct list *next;
} SLIST;
SLIST *deletelist(SLIST * p,int *pvalue)
{
SLIST *todel, *head = p;
while(p && p->next) {
if (p->next->data == *pvalue) {
todel = p->next;
p->next = todel->next;
free(todel);
} else {
p = p->next;
}
}
return head;
}
SLIST *creatlist(int *a)
{
SLIST *h,*p,*q; int i;
h=p=(SLIST *)malloc(sizeof(SLIST));
for(i=0; i<N; i++)
{ q=(SLIST *)malloc(sizeof(SLIST));
q->data=a[i];
p->next=q;
p=q;
}
p->next=0;
return h;
}
void outlist(SLIST *h)
{
h = h->next;
while (h) {
printf("%d ", h->data);
h = h->next;
// if (h) {
// printf(" ");
// }
}
printf("\n");
}
int main(void)
{
SLIST *head;
int nvalue,i;
int a[N];
for(i=0;i<N;i++)
{
scanf("%d",&a[i]);
}
scanf("%d",&nvalue);//删除的结点数据
head=creatlist(a);
head=deletelist(head,&nvalue);
outlist(head);
return 0;
}