1. 程式人生 > >C經典之14-雙向鏈表存儲1-10---ShinePans

C經典之14-雙向鏈表存儲1-10---ShinePans

edit 文件 ber post popu ng-click ans toupper ack

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>  //system(); 這個指令須要用到此頭文件
#include <ctype.h> //toupper要用到
#include <malloc.h> //在內存管理時用到的頭文件
void main()
{
	int i;

	struct ListEntry{
		int number;  //數據域
		struct ListEntry *next;  //指向 下一個ListEntry節點的指針
		struct ListEntry *previous; //指向上一個 ListEntry節點的指針
	}start,*node, *newOne;
	
	start.next = NULL;  //置空鏈表
	start.previous = NULL;
	node = &start;  //指向鏈表的開始
	
	for (i = 1; i < 10; i += 2)
	{
		node->next = (struct ListEntry*)malloc(sizeof(struct ListEntry));
		node->next->previous = node;
		node = node->next;
		node->number = i;
		node->next = NULL;
	}
	for (i = 2; i <= 10; i += 2)
	{
		int found = 0;
		
		newOne = (struct ListEntry*)malloc(sizeof(struct ListEntry));
		newOne->number = i;
		node = start.next;

		do{
			if (node->number > newOne->number)
			{
				newOne->next = node;
				newOne->previous = node->previous;
				node->previous->next = newOne;
				node->previous = newOne;
				found = 1;
			}
			else{
				node = node->next;
			}
			}while ((node->next) && (!found));
			if (!found)
			if (node->number > newOne->number)
			{
				newOne->next = node;
				newOne->previous = node->previous;
				node->previous->next = newOne;
				node->previous = newOne;
			}
			else{
				newOne->next = NULL;
				newOne->previous = node;
				node->next = newOne;
			}
		}
		node = start.next;
		do{
			printf("%d", node->number);
			node = node->next;
		} while (node);
	system("pause");
}


技術分享圖片



這個代碼很經典,將1-10 不按書順序存入雙向鏈表,而且又一次編排,使其終於輸出 為 12345678910

C經典之14-雙向鏈表存儲1-10---ShinePans