C 单链表的顺序插入

来源:互联网 发布:java中的多线程 编辑:程序博客网 时间:2024/05/12 08:30

思路: 向单链表中插入一个新值,需要插入位置前后的两个节点。

            从根节点开始遍历,寻找插入的正确位置。

struct node {int v;struct node *p; };int fun (struct node **rootp,int val){struct node *current;struct node *previous;struct node *newp;current = *rootp;previous = NULL;newp = (struct node *)malloc(sizeof(struct node));if( newp == NULL)return 0;while( current != NULL &&  (current->v < val)){previous = current;current = current->p;}newp->v = val;newp->p = current;if(previous == NULL)*rootp = newp;elseprevious->p = newp;return 1;}


 

 

0 0