有序双链表的建立
来源:互联网 发布:mysql order by count 编辑:程序博客网 时间:2024/06/05 20:27
/***把一个值插入到一个有序双链表,first是一个指向根节点的指针,**newValue是欲插入的新值。**返回值:如果欲插值原先已存在于链表中,函数返回0;**如果内存不足导致无法插入,函数返回-1;如果插入成功,函数返回1。*/#include <stdio.h>#include <stdlib.h>typedef struct NODE{ struct NODE *left; struct NODE *right; int value; }Node;int dListInsert(Node **first,int newValue){ Node *current = *first; Node *newNode,*pre = NULL; while(current != NULL && current->value < newValue) { pre = current; current = current->right; } if(current != NULL && current->value == newValue) return 0; newNode = (Node *)malloc(sizeof(Node));newNode->value = newValue; if(newNode == NULL) return -1; newNode->right = current; //1 newNode->left = pre; //2 if(current != NULL) //链表非空并且插入位置不在链表尾部 current->left = newNode; //3 if(current == *first) //新节点插入位置为链表首部或者链表本身为空 *first = newNode; else pre->right = newNode; //4 return 1; }/***测试用,输入无序整数,通过调用dListinsert(),**建立有序且节点值不重复的双链表,然后打印之。*/int main(void){ Node *head = NULL; Node *temp; int count,value; count = 8; //测试整数的个数 printf("请输入%d个整数:\n",count); while(count--) { scanf("%d",&value);dListInsert(&head,value); } temp = head; while(temp) { printf("%d ",temp->value); temp = temp->right; } printf("\n"); return 0;}