经典面试题--点链表之无头插入

来源:互联网 发布:淘宝的模特是怎么找的 编辑:程序博客网 时间:2024/04/27 14:37

问题描述: p指向了一个某个位置,在p的前面插入成员,

再简单头插图,tmp ->next = phead ->next ;phead->next = tmp;就ok!

相信大家在通过上一篇的阅读都有了一点想法:http://blog.csdn.net/qq_35256722/article/details/52625686

现在我们讨论一下想法:

       p指向了一个某个位置,在p的前面插入,几乎没想法,忘了上一篇了,继续换。

      将tmp 先插到p的后面,这个应该改很简单 tmp ->next = p->next;

p->next = tmp;完了就这样了,然后tmp的值和p的值进行交换,最后编程tmp

插到了p的前面:嘿嘿!

     代码:

<span style="font-size:18px;">static void swap (void *e1,void *e2,size_t  lenth){void *tmp = malloc( lenth);memmove(tmp,e2,lenth);memmove(e2,e1,lenth);memmove(e1,tmp,lenth);free(tmp);}</span>


<span style="font-size:18px;">static NODE *alloc_node(elem_type e)//tmp生成,tmp->next = NULL;{NODE *tmp = (NODE *)malloc(sizeof(NODE));assert(tmp !=NULL);tmp->data = e;tmp->next = NULL;return tmp;}</span>
<span style="font-size:18px;">bool insert_no_head(NODE  *p, elem_type e) { NODE *s = p->next; NODE *tmp = alloc_node(e); if(p == NULL) { return false; } tmp->next = p->next; p->next = tmp; swap(&p->data,&tmp->data,sizeof(elem_type)); return true;  }</span>
哈哈,看完你也需会说,这是插到p的前面了吗?结论很肯定,是插到了。

 



1 0
原创粉丝点击