鏈表——創建及功能函數

//頭文件 Node.h
#ifndef  _Node_
#define  _Node_

typedef struct _node {
	int number;
	struct _node *next;
}Node;

#endif // ! _node_

//頭文件 List.h
#ifndef _LIST_
#define _LIST_

#include "Node.h"

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

#endif // !_LIST_

//頭文件 List_OP.h
#ifndef _LIST_OP_
#define _LIST_OP_

#include <stdio.h>
#include <stdlib.h>
#include "Node.h"
#include "List.h"

void add_list(List *plist, int num) {	//添加鏈表的節點
	Node *last = NULL;
	last = plist->head;
	Node *p = (Node *)malloc(sizeof(Node));
	p->number = num;
	p->next = NULL;
	if (last) {	//當last爲NULL時,last->next無意義
		while (last->next) {
			last = last->next;
		}
		last->next = p;
	}
	else {
		plist->head = p;//最開始時,讓p來當頭指針
	}
}

void print_list(List list) {	//完成輸入後打印整串鏈表
	Node *p;
	for (p = list.head; p; p = p->next) {
		printf("%d\n", p->number);
	}
}

void search_list(List list, int srch) {	//查找是否存在所找項
	Node *p;
	int i = 1;
	int IsFound = 0;
	for (p = list.head; p; i++,p = p->next) {
		if (p->number == srch) {
			printf("Found! Locate at number %d\n", i);
			IsFound = 1;
			break;
		}
	}
	if (IsFound == 0) {
		printf("Not Found!\n");
	}
}

void delet_list(List list, int srch) {	//如果找到,刪除節點
	Node *q, *p;
	int IsFound = 0;
	for (q = NULL, p = list.head; p; q = p, p = p->next) {
		if (p->number == srch) {
			if (q) {
				q->next = p->next;
			}
			else {
				list.head->next = p->next;
			}
			free(p);
			IsFound = 1;
			printf("Delete!\n");
			break;
		}
	}
	if (IsFound == 0) {
		printf("CANNOT DO IT!\n");
	}
	printf("New List:\n");
	print_list(list);
}

#endif // ! _LIST_OP_

//主函數
#include <stdio.h>
#include <stdlib.h>
#include "Node.h"
#include "List.h"
#include "List_OP.h"

void add_list(List *plist, int num);
void print_list(List list);
void search_list(List list, int srch);
void delet_list(List list, int srch);

int main() {
	int num = 0;
	List list;
	list.head = NULL;
	do {
		printf("input the number\n");
		scanf("%d", &num);
		if (num != -1) {
			add_list(&list, num);
		}
	} while (num != -1);
	print_list(list);
	int srch = 0;
	//int IsFound = 0;	//值作爲是否執行刪除函數的標誌
	printf("input a number to search the list\n");
	scanf("%d", &srch);
	search_list(list, srch);
	delet_list(list, srch);
	return 0;
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章