更新了,关于单链表的一些总结:- #include<stdio.h>
- #include<stdlib.h>
- #include<time.h>
- #include<assert.h>
- #define FALSE 0
- #define TRUE 1
- // 单链表声明
- typedef struct NODE
- {
- struct NODE *link;
- int value;
- }Node;
- // 插入函数 效率不错
- int sll_insert(register Node **linkp , int new_value)
- {
- register Node *current;
- register Node * news;
- /*寻找正确的插入位置,方法是按顺序访问链表,直到到达值大于或等于新插入值的节点*/
- while((current = *linkp) != NULL && current->value < new_value)
- {
- linkp = ¤t->link;
- }
- /* 为新节点分配内存,并把新值存入到新节点中,如果内存分配失败,函数返回FALSE*/
- news = (Node *) malloc(sizeof(Node));
- if(news == NULL)
- return FALSE;
- news->value =new_value;
- /* 把新节点插入到链表中,并返回TRUE*/
- news->link =current;
- *linkp = news;
- return TRUE;
- }
- // 在链表中寻找特定的值,返回链表节点指针
- Node * sll_find(Node *first,int desired_value)
- {
- for(;first!=NULL;first=first->link)
- if(first->value == desired_value)
- return first;
- return NULL;
- }
- //打印链表数据
- void printSll(Node *root)
- {
- while(root!=NULL)
- {
- printf("%d\n",root->value);
- root = root->link;
- }
- }
- //输出链表节点个数
- int sll_count(Node *first)
- {
- int count=0;
- for(;first!=NULL;first=first->link)
- count++;
- return count;
- }
- // 反序排列一个单链表所有节点,返回指向单链表的新头节点指针
- Node * sll_reverse(Node *current)
- {
- Node *previous;
- Node *next;
- for(previous = NULL;current != NULL; current =next)
- {
- next = current->link;
- current->link = previous;
- previous = current;
- }
- return previous;
- }
- // 功能:单链表中删除指定节点。
- // 参数:第一个参数指向链表的根指针,第二个参数指向需要被删除的节点。
- // 返回:成功返回TRUE,否则FALSE。
- int sll_remove(Node **linkp,Node *del)
- {
- register Node *current;
- assert(del!=NULL);
- // 寻求要删除的节点
- while((current = *linkp) != NULL && current != del)
- linkp = ¤t->link;
- if(current == del)
- {
- *linkp = current->link;
- free(current);
- return TRUE;
- }
- else
- return FALSE;
- }
|