list_splice (拼接两个链表)

本文详细介绍了链表拼接的实现方法,通过具体代码示例展示了如何将两个链表进行合并,同时提供了完整的C语言代码实现,包括链表节点定义、链表拼接函数以及拼接后的遍历和删除操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    /* 拼接两个链表:
        1.如果新增的链表只有一个链表头就不做任何处理(因为链表头不包含数据)
        2.    (head      2)     +    (add  4  5)    
            ==> (head     (5      6)   2   3)        // 抛弃链表头add
    */

    /* Join two lists.  */
    static inline void list_splice (list_t *add, list_t *head)
    {
      /* Do nothing if the list which gets added is empty.  */
      if (add != add->next)
        {
          add->next->prev = head;            // 5的上一项是head
          add->prev->next = head->next; // 6的下一项是2
          head->next->prev = add->prev; // 2的上一项是6
          head->next = add->next;           // head的下一项是5
        }
    }


举例:

#include "list.h"
#include <stdio.h>

static LIST_HEAD (head);	
static LIST_HEAD (head2);	
typedef struct T
{	char *name;
	list_t member;	// pre, next
}type;

int main(int argc, char **argv)
{
	type a,b,c,d;
	list_t *ptr;	// 节点指针
	type *t;
	
	a.name = "a";
	b.name = "b";
	c.name = "c";
	d.name = "d";
	list_add(&a.member, &head); // 紧挨着链表头插入新节点
	list_add(&b.member, &head); // 紧挨着链表头插入新节点
	
	list_add(&c.member, &head2); // 紧挨着链表头插入新节点
	list_add(&d.member, &head2); // 紧挨着链表头插入新节点

	list_splice(&head2, &head);
	list_for_each_prev(ptr, &head)
	//for (pos = (head)->prev; pos != (head); pos = pos->prev)
	{	t = list_entry(ptr, type, member);
		printf("%s\n", t->name);
		list_del(ptr);
	}
	return 0;
}
/* 结果:
	book@gui_hua_shu:~/test$ ./a.out
	a
	b
	c
	d
*/

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值