鏈表之頭插法,尾插法,顯示,長度,查找位置(兩種),刪除

# include<stdio.h>
# include<stdlib.h>
using namespace std;

typedef struct node
{
	int data;
	struct node * next;
}Node;
int len_list(Node * head)//鏈表長度
{
	Node* pt = head->next;
	int len = 0;
	while (pt)
	{
		len++;
		pt = pt->next;
	}

#if 0
	while (head->next)
	{
		len++;
		head->next = head->next->next;
	}
#endif
	return len;
}
int search_list(Node * head ,int search_data)//鏈表查找
{
	int loc = 0;
	int loc1 = 0;
	Node * pt = head->next;
	while (pt)
	{
		if (pt->data == search_data)
		{
			loc = loc1;
		}
		pt = pt->next;
		loc1++;
	}
	if (loc == 0)
	{
		printf("查無此數!!!");
		return -1;
	}
	else
	{
		return loc;
	}
	
}
Node * search_list_Node(Node * head, int search_data)
{
	head = head->next;
	while (head)
	{
		if (head->data == search_data)
			break;
		head = head->next;
	}
	if (head == NULL)
	{
		printf("查無此項!!!\n");
	}
	return head;
}


Node * creat_list_first()//頭插法
{
	Node * head = (Node *)malloc(sizeof(Node));
	head->next = NULL;
	Node * cur = NULL;
	int data;
	printf("請輸入節點數據:\n");
	scanf("%d", &data);
	while (data)
	{
		cur = (Node *)malloc(sizeof(Node));
		cur->data = data;
		cur->next = head->next;
		head->next = cur;
		scanf("%d", &data);
	}
	return head;
}

Node * creat_list_end()//尾插法
{
	Node * head = (Node*)malloc(sizeof(Node));
	head->next = NULL;
	Node * cur = NULL;
	Node * pt = head;
	int data;
	printf("請輸入節點數據:\n");
	scanf("%d", &data);

	while (data)
	{
		cur = (Node *)malloc(sizeof(Node));
		cur->data = data;
		cur->next = NULL;
		pt->next = cur;
		pt = cur;	
		scanf("%d", &data);
	}
	return head;
}
void show_list(Node * head)//顯示鏈表
{
	Node * phead = head->next;
	while (phead)
	{
		printf("%d\n", phead->data);
		phead = phead->next;
	}
}
void  delete_data(Node*head, int data)
{
	Node * loc_list = search_list_Node(head, data);
	//head = head->next;之所以沒有這句是爲了保證鏈表的結構完整性,加上該句的話會使鏈表喪失頭結點
	while (head->next != loc_list) head = head->next;//此處說明是待查找數據的前一項節點;

	head->next = loc_list->next;
	free(loc_list);
	
}


int main()
{
	Node * head = (Node *)malloc(sizeof(Node));
	
	head = creat_list_end();
	show_list(head);

	search_list_Node(head, 4);

	printf("鏈表長度:%d\n", len_list(head));
	printf("查找數據所在位置:%d\n", search_list(head, 4) + 1);
	delete_data(head, 4);
	show_list(head);
	return 0;
}


下一步準備練習,鏈表的排序:1.交換值,2.交換指針

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