思路: 向单链表中插入一个新值,需要插入位置前后的两个节点。
从根节点开始遍历,寻找插入的正确位置。
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;
else
previous->p = newp;
return 1;
}