c语言将一单链表和一循环链表合成一个单链表,且算法复杂度与链表长度无关(17)

在这里插入图片描述

代码:

#include<stdio.h>
#include<stdlib.h>
#include<assert.h>


//因为需要算法复杂度与链表长度无关,所以使用带尾指针的循环链表
//这里假设单链表没有为尾点指针
//另外要注意释放循环链表的头节点

typedef struct node
{
	int data;
	struct node* next;
	
}Node;

typedef struct list
{
	Node* head;
	Node* tail;
	int length;

}List;

void Init_oneside_list(List* L)
{
	Node* first = (Node*)malloc(sizeof(Node));
	if(!first)
		printf("wrong!\n");
	first -> data = 0;
	first -> next = NULL;
	L->head = L->tail = first;

	int length;

	printf("please enter list length: ");
	scanf("%d",&length); //scanf里面不能写类似于printf中打印字符串的语句
	for(int i = 0; i< length; i++)
	{
		Node* new = (Node*)malloc(sizeof(Node));
		scanf("%d",&new -> data); //这个语句注意一下

		new -> next = NULL;
		L->tail -> next = new;
		L->tail = new;

	}


}


void Init_cicle_list(List * L)
{
	Node* first = (Node*)malloc(sizeof(Node));
	assert(first != NULL);

	first->data = 0;
	first->next = L->head;
	L->head = L->tail = first;
	L->length = 0;

	//尾插法建立链表
	int size;
	printf("please enter the list length: ");
	scanf("%d",&size);
	for(int i = 0;i < size; i++)
	{
		Node* new = (Node*)malloc(sizeof(Node));
		int number;
		scanf("%d",&number);
		new -> data = number;

		L->tail->next = new;
		L->tail = new;
		L->tail->next = L->head; //这里不要写的是L->tail->next = L->head->next 因为这是指针之间的赋值

		L->length ++;
	}

}


void merge(List* ha,List hb)
{
	hb.head = hb.tail->next;
	hb.tail -> next = ha->head->next;
	ha->head->next = hb.head->next;

	free(hb.head);

}


void print_list(List L)
{
	Node* p;
	p = L.head->next;

	while(p != NULL)
	{
		printf("%d ",p->data);
		p = p -> next;
	}

	printf("\n");
}

int main(int argc, char const *argv[])
{
	List ha,hb;
	Init_oneside_list(&ha);
	Init_cicle_list(&hb);


	merge(&ha,hb);

	print_list(ha);

	

	return 0;
}

运行截图:
在这里插入图片描述

我决定明天也分单双号题来做了,不然这一直做这一种类型的题,真的会很烦的。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

五月的天气

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值