面试题目--合并两个有序单链表

题目

一个面试题目,将两个递增的有序单链表合并成一个递增单链表。有两种理解:
1、new一个单链表,返回新的头节点
2、在原链表上操作,返回新的头节点
第一种实现较为简单,只需要从头比较链表的节点,将较小的插入新链表,被插入的节点指针后移,直至遍历整个链表。而在原表操作就相对复杂一点,主要有三部分:首先确定返回的头节点,中间遍历重定向链表指针,当某一个链表先遍历完之后末尾的处理。在原表操作的代码如下:

#include 
using namespace std;

struct node{
     
	int val;
	node *next;
	node(int a) :val(a), next(nullptr) {
     }
};

node* sortnode(node* head1, node* head2){
     
	node *newhead;
	node *prenode1 = head1;
	node *prenode2 = head2;
	head1 = head1->next;
	head2 = head2->next;
	if (prenode1->val <= prenode2->val){
     
		newhead = prenode1;
	}
	else if (prenode1->val > prenode2->val){
     
		newhead = prenode2;
	}
	while (head1 != nullptr && head2 != nullptr){
     
		if (prenode1->val <= prenode2->val){
     
			if (head1->val >= prenode2->val){
     
				prenode1->next = prenode2;
				prenode1 = head1;
				head1 = head1->next;
				continue;
			}
			prenode1 = head1;
			head1 = head1->next;
		}
		if (prenode2->val <= prenode1->val){
     
			if (head2->val >= prenode1->val){
     
				prenode2->next = prenode1;
				prenode2 = head2;
				head2 = head2->next;
				continue;
			}
			prenode2 = head2;
			head2 = head2->next;
		}
	}	
	if (head2 == nullptr && head1 != nullptr){
     
		while (prenode1->val <= prenode2->val){
     
			if (head1->val >= prenode2->val){
     
				prenode1->next = prenode2;
				prenode1 = head1;
				head1 = head1->next;
				break;
			}
			prenode1 = head1;
			head1 = head1->next;
		}
		prenode2->next = prenode1;
	}
	else if (head1 == nullptr && head2 != nullptr){
     
		while (prenode2->val <= prenode1->val){
     
			if (head2->val >= prenode1->val){
     
				prenode2->next = prenode1;
				prenode2 = head2;
				head2 = head2->next;
				break;
			}
			prenode2 = head2;
			head2 = head2->next;

		}
		prenode1->next = prenode2;
	}

	else{
     
		if (prenode1->val <= prenode2->val){
     
			prenode1->next = prenode2;
		}
		else{
     
			prenode2->next = prenode1;
		}
	}
	return newhead;
}

void print(node *head){
     
	node *cur = head;
	while (1){
     
		if (cur != nullptr){
     
			cout << cur->val << " ";
			cur = cur->next;
		}
		else{
     
			cout << endl;
			break;
		}
	}
}

int main() {
     
	node *head1 = new node(3);
	node *cur = head1;
	for (int i = 4; i < 4; ++i){
     
		cur->next = new node(2 * i);
		cur = cur->next;
	}
	node *head2 = new node(3);
	cur = head2;
	for (int i = 5; i < 5; ++i){
     
		cur->next = new node(i);
		cur = cur->next;
	}
	print(head1);
	print(head2);
	node *head = sortnode(head1, head2);
	print(head);
	return 0;
}

运行结果:

面试题目--合并两个有序单链表_第1张图片
面试题目--合并两个有序单链表_第2张图片
面试题目--合并两个有序单链表_第3张图片
总感觉实现很复杂,如果有好的解决方法,欢迎评论区讨论。

你可能感兴趣的:(c++,单链表,合并排序,链表)