如 list1={2,4,5,6,8,9};list2={1,3,7};
合并的新链表list3={1,2,3,4,5,6,7,8,9}
面试的时候脑子有点乱,没有写出来,答案可能不完善,有漏洞,如有发现,请留言。
#include <iostream>
#include <stdio.h>
using namespace std;
struct ListNode//链表定义
{
int val;
struct ListNode *next;
};
ListNode* create(int arr[], int n)//丛数组读取元素组成链表
{
if (arr == NULL || n <= 0)
return NULL;
ListNode *head = (ListNode*)malloc(sizeof(struct ListNode));
head->val = arr[0];
head->next = NULL;
ListNode *tmp = head;
ListNode *next = NULL;
for (int i = 1; i < n; i++)
{
next = (ListNode*)malloc(sizeof(struct ListNode));
if (next)
{
next->val = arr[i];
next->next = NULL;
tmp->next = next;
tmp = next;
}
}
return head;
}
//调用链表打印函数,打印出合并后的链表元素,代码如下:
void printList(struct ListNode *head)
{
if (head == NULL)
return;
while (head)
{
printf("%d ", head->val);
head = head->next;
}
}
ListNode* createList(struct ListNode * list1, struct ListNode* list2)//合并 并排好序
{
if (list1 == NULL && list2 == NULL)
return NULL;
ListNode *head = (ListNode*)malloc(sizeof(struct ListNode));//记录链表头指针
if (list1->val < list2->val)
{
head->val = list1->val;
list1 = list1->next;
head->next = NULL;
}
else
{
head->val = list2->val;
list2 = list2->next;
head->next = NULL;
}
ListNode *temp = head;//记录当前链表指针位置
ListNode *next = NULL;//记录正在操作的元素指针
while (list1&&list2) {
next = (ListNode*)malloc(sizeof(struct ListNode));
if (list1->val < list2->val)
{
next->val = list1->val;
next->next = NULL;
list1 = list1->next;
temp->next = next;
temp = next;
}
else
{
next->val = list2->val;
next->next = NULL;
list2 = list2->next;
temp->next = next;
temp = next;
}
}
while (list1)
{
next = (ListNode*)malloc(sizeof(struct ListNode));
next->val = list1->val;
next->next = NULL;
list1 = list1->next;
temp->next = next;
temp = next;
}
while (list2)
{
next = (ListNode*)malloc(sizeof(struct ListNode));
next->val = list2->val;
next->next = NULL;
list2 = list2->next;
temp->next = next;
temp = next;
}
return head;//返回链表头指针
}
int main()
{
int arr1[] = { 2,4,5,6,8,9 };
int arr2[] = { 1,3,7 };
ListNode* list1 = create(arr1, 6);
ListNode* list2 = create(arr2, 3);
printList(list1);
cout << endl;
printList(list2);
ListNode* list3= createList(list1,list2);
cout << endl;
printList(list3);
}