题目:设ha和hb分别是两个带附加头结点的非递减有序单链表的头指针。将两个表合并成一个非递增有序单链表。结果不能占用除两个链表外多余的存储空间。
我的思路:先合并成非递减有序,然后再翻转链表,
不知道有没有比这更好的办法,先写在这
代码:
main.c
#include"list.h"
int main(void)
{
node * ha = list_init();
node * hb = list_init();
int arr1[]= {1,3,4,4,9,10};
int arr2[]= {2,3,4,13,13,14};
int n = sizeof(arr1) / sizeof(*arr1);
int m = sizeof(arr2) / sizeof(*arr2);
list_create(ha, arr1, n);
list_show(ha);
list_create(hb, arr2, m);
list_show(hb);
merge(ha,hb);
list_show(ha);
turn(ha);
list_show(ha);
return 0;
}
list.c
#include "list.h"
node *list_init()
{
node *ptr = malloc(sizeof(node));
if (ptr == NULL)
return NULL;
ptr->next = NULL;
return ptr;
}
void list_create(node *ptr, int *a, int n)
{
node *p = ptr;
for (int i = 0; i < n; i++)
{
node *new = malloc(sizeof(node));
if (new == NULL)
exit(1);
new->next = NULL;
new->data = a[i];
p->next = new;
p = new;
}
}
void list_show(node *ptr)
{
node *p = ptr;
while (p->next != NULL)
{
p = p->next;
printf("%d ", p->data);
}
printf("\n");
}
void merge(node *ha,node *hb)
{
node *pa = ha->next;
node *pb = hb->next;
node *p = ha, *q = NULL;
while (pa != NULL && pb != NULL)
{
if (pa->data > pb->data)
{
q = pb;
pb = pb->next;
p->next = q;
q->next = pa;
p = p->next;
}
else
{
pa = pa->next;
p = p->next;
}
}
if(pa == NULL)
p->next = pb;
}
void turn(node *ha)
{
node *pa = ha->next;
node *tail = NULL;
node *current = ha;
while (current->next != NULL)
current = current->next;
tail = current;
node * head = pa;
while(head != tail)
{
current = head;
head = head->next;
current->next = tail->next;
tail->next = current;
}
ha->next = tail;
}
list.h
#ifndef __list_H__
#define __list_H__
#include<stdio.h>
#include<stdlib.h>
typedef struct node_st
{
int data;
struct node_st * next;
}node;
node *list_init();
void list_show(node *ptr);
void list_create(node *ptr, int *a, int n);
void merge(node *ha,node *hb);
void turn(node *ha);
#endif