代码:
#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;
}
运行截图:
我决定明天也分单双号题来做了,不然这一直做这一种类型的题,真的会很烦的。。。