1.28实验:探究一个好的数据结构对链表的影响(本实验为改进代码实验)

1.28课后实验

实验目的:探究一个好的数据结构对链表的影响(本实验为改进代码实验)

😆原代码如下

#include<stdio.h>
#include<stdlib.h>
typedef struct _node{//定义节点 
	int value;
	struct _node *next; 
}Node;//套娃内味 

Node** add(Node** phead, int num);

int main() {
	int num;

	Node *head = NULL;
	do {
		scanf("%d", &num);
		if (num != -1) {
			//add to linked-list
			head = *add(&head, num);
		}
	} while (num != -1);
    //output
	for (Node* i = head; i != NULL; i = i->next) {
		printf("%d", i->value);
	}
}

Node** add(Node** phead, int num) {
	Node *p = (Node*)malloc(sizeof(Node));
	p->value = num;
	p->next = NULL;
	//find the last
	Node *last = *phead;
	if (last) {
		while (last->next) {
			last = last->next;
		}
		//attach
		last->next = p;
	} else {
		*phead = p;
	}
	return phead;
}


在上面的程序中,

我们把add提到外面去封装成一个函数,并且依然保证着head改了,但是老师说其实也还有更好的办法,但是把这个办法留给我们,就是在外面定义一个list的数据结构,而且这个数据结构还可以有头有尾,下面就让我们尝试一下这种实现方法吧!

typedef struct _list{
	Node *head;
	Node *tail;
}list;

这就是所说的结构,于是我们的函数先初步改成这样,即把head都改成list.head,add函数也可以不用传值:

typedef struct _list{
	Node *head;
	Node *tail;
}List;

void add(Node** phead, int num);

int main() {
	int num;
	List list;
	list.head=list.tail=NULL;
	
	do {
		scanf("%d", &num);
		if (num != -1) {
			//add to linked-list
		add(&list.head, num);
		}
	} while (num != -1);
    //output
	for (Node* i = list.head; i != NULL; i = i->next) {
		printf("%d", i->value);
	}
}


void add(Node** phead, int num) {
	Node *p = (Node*)malloc(sizeof(Node));
	p->value = num;
	p->next = NULL;
	//find the last
	Node *last = *phead;
	if (last) {
		while (last->next) {
			last = last->next;
		}
		//attach
		last->next = p;
	} else {
		*phead = p;
	}
}

接下来改tail才是重头戏,因为原来的add函数每次都要从head开始搜索,比较多余,于是我们应该可以每次记录最后的那个节点为tail,如下,

#include"node.h"
#include<stdio.h>
#include<stdlib.h>
//typedef struct _node{//定义节点
//	int value;
//	struct _node *next;
//}Node;
typedef struct _list{
	Node *head;
	Node *tail;
}List;

void add(List *list,int num);

int main() {
	int num;
	//initialize
	List list;
	list.head=NULL;
	list.tail=NULL;
	//input 
	do {
		scanf("%d", &num);
		if (num != -1) {
		//add to linked-list
		add(&list,num);
		}
	} while (num != -1);
	//output
	for (Node* i = list.head; i != NULL; i = i->next) {//从表头开始读起,当读到NULL时,终止 
		printf("%d", i->value);
	}
}

void add(List *list,int num){
	//等待输入的节点 
	Node *p = (Node*)malloc(sizeof(Node));//分配一个Node类型大小的内存空间, 并把它赋给Node*型的变量p
	p->value = num;
	p->next = NULL;
	if(list->tail){
		list->tail->next=p;//每次将表尾与新插入元素连接起来 
		(list->tail)=list->tail->next;//并记录新表尾 
	}else {//必须执行一次初始化,即先插入表头,并让表尾等于表头 
		list->head=p;
		list->tail=list->head; 
	}
}
	
//	Node *last = list->head;
//	if (last) {
//		while (last->next) {
//			last = last->next;
//		}
//		//attach
//		last->next = p;
//	} else {
//		list->head = p;
//	}	



😂😂😂现在1.30了终于写对了,玩的。

posted @ 2022-01-30 12:44  Link_kingdom  阅读(57)  评论(0编辑  收藏  举报