数据结构和算法实验指导书 下载本文

内容发布更新时间 : 2024/5/15 21:24:23星期一 下面是文章的全部内容请认真阅读。

WORD格式可编辑 p=p->next; }

return 0; }

main()

{ SLIST *head; int k; char ch; char a[N]={'m','p','g','a','w','x','r','d'}; head=creatlist(a); outlist(head);

printf(\ scanf(\ k=fun(head,ch);

if (k==0) printf(\

else printf(\}

SLIST *creatlist(char *a) {

int i;

SLIST *tou,*p;

tou=(SLIST*)malloc(sizeof(SLIST)); //创建并初始化头结点 tou->data=N; tou->next=NULL;

for(i=0;i

p=(SLIST*)malloc(sizeof(SLIST)); p->data=a[i];

p->next=tou->next; tou->next=p; }

return tou; }

void outlist(SLIST *h) { SLIST *p; p=h->next;

if (p==NULL) printf(\ else

{ printf(\ do

{ printf(\ while(p!=NULL); printf(\ } }

专业知识分享

WORD格式可编辑

3、//去偶操作,链表中各节点按数据域递增有序链接,函数fun的功能是,删除链表中数据域值相同的节点,使之只保留一个

#include #include #define N 8 typedef struct list { int data;

struct list *next; } SLIST;

void fun( SLIST *h) {

SLIST *p,*shanchu; //用于遍历的指针p,用于删除的指针shanchu p=h->next; /p为寿元节点 while(p->next!=NULL) //终止条件 {

if(p->data==p->next->data) //判断是否有重复原素 {

shanchu=p->next;

p->next=shanchu->next; free(shanchu); } else

p=p->next; } }

SLIST *creatlist(int *a)

{ SLIST *h,*p,*q; int i;

h=p=(SLIST *)malloc(sizeof(SLIST)); for(i=0; i

{ q=(SLIST *)malloc(sizeof(SLIST)); q->data=a[i]; p->next=q; p=q; }

p->next=0; return h;

专业知识分享

WORD格式可编辑 }

void outlist(SLIST *h) { SLIST *p; p=h->next;

if (p==NULL) printf(\ else

{ printf(\

do { printf(\ printf(\ } }

main( )

{ SLIST *head; int a[N]={1,2,2,3,4,4,4,5}; head=creatlist(a);

printf(\ fun(head);

printf(\}

4、//在main函数中多次调用fun函数,每调用一次fun函数,输出链表尾部节点中的数据,并释放该节点,使得链表缩短。

#include #include #define N 8 typedef struct list { int data;

struct list *next; } SLIST;

void fun( SLIST *p) {

SLIST *bianli,*shanchu; //遍历,删除 bianli=p; while(bianli->next->next!=NULL) {

bianli=bianli->next;

}

printf(\ //输出

专业知识分享

WORD格式可编辑 shanchu=bianli->next; //释放 free(shanchu); bianli->next=NULL; }

SLIST *creatlist(int *a)

{ SLIST *h,*p,*q; int i;

h=p=(SLIST *)malloc(sizeof(SLIST)); for(i=0; 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; p=h->next;

if (p==NULL) printf(\ else

{ printf(\

do { printf(\ printf(\ } }

main()

{ SLIST *head;

int a[N]={11,12,15,18,19,22,25,29}; head=creatlist(a);

printf(\ printf(\ while (head->next != NULL){ fun(head);

printf(\

printf(\ } }

专业知识分享

WORD格式可编辑

5、实现约瑟夫环函数(选做) #include #include typedef struct list { int data;

struct list *next; } SLIST;

SLIST *creatlist(int m) {

int i;

SLIST *tou,*p,*wei; //头指针 生成节点指针 尾指针 tou=(SLIST*)malloc(sizeof(SLIST)); //头节点 wei=tou;

专业知识分享