C经典之14-双向链表存储1-10---ShinePans
#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