#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int data;
struct node *pre;
struct node *next;
} Node;
int get_int(void);
Node* get_node(void);
void insert(Node*p,Node* new_node);
int
main()
{
Node * p;
Node * head = (Node*)malloc(sizeof(Node));
head->pre = NULL;
head->next = get_node();
head->next->pre = head;
printf("please enter the number 'q' to quit:");
while (1)
{
p = get_node();
p->data = get_int();
if (p->data ==0)
break;
insert(head,p);
}
while (head->next!=NULL)
{
printf("%d ",head->next->data);
head->next = head->next->next;
}
return 0;
}
//得到整數
int
get_int(void)
{
int input;
char ch;
while (scanf("%d",&input)!=1)
{
while((ch=getchar())!='\n')
putchar(input);
printf(" is not an integer.\nPlease enter an integer value,such as 25,-178,or 3;\n");
}
return input;
}
//向鏈表插入新鏈
void
insert(Node*p,Node* new_node)
{
if (p->next->data == 0)
{
p->next->data = new_node->data;
return;
}
Node* scan = p->next;
while (1)
{
if (scan->data < new_node->data)
{
if (scan->next != NULL)
scan = scan->next;
else
{
scan->next = new_node;
new_node->pre = scan;
break;
}
}
else
{
new_node->pre = scan->pre;
new_node->next = scan;
scan->pre->next = new_node;
scan->pre = new_node;
break;
}
}
}
//獲得新節點
Node*
get_node(void)
{
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->next = NULL;
new_node->pre = NULL;
new_node->data = 0;
return new_node;
}
考慮到雙鏈表容易增加刪除鏈的性質,每輸入一個數據就立即將其插入到鏈表中,輸入完成排序也完成
雙鏈表排序問題(C語言)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.