专访:合并两个排序单链表

编程入门 行业动态 更新时间:2024-10-11 01:15:23
本文介绍了专访:合并两个排序单链表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这是一个编程问题接受记者采访时笔试时提出。 你有两个已排序单链表,你必须把它们合并,并返回新列表的头部,而无需创建任何新的额外的节点。返回的列表应该进行排序,以及

该方法的签名是:     节点MergeLists(List1的节点,节点list2中);

节点类如下:

类节点{     int数据;     下一节点; }

我尝试了许多解决方案,但没有创造额外的节点螺丝的东西。请大家帮帮忙。

下面是附带的博客文章techieme.in/merging-two-sorted-singly-linked-list/

解决方案

节点MergeLists(List1的节点,节点list2中){   如果(List1的== NULL)返回list2中;   如果(list2中== NULL)返回List1中;   如果(list1.data< list2.data){     list1.next = MergeLists(list1.next,list2中);     返回List1中;   } 其他 {     list2.next = MergeLists(list2.next,List1中);     返回list2中;   } }

This is a programming question asked during a written test for an interview. "You have two singly linked lists that are already sorted, you have to merge them and return a the head of the new list without creating any new extra nodes. The returned list should be sorted as well"

The method signature is: Node MergeLists(Node list1, Node list2);

Node class is below:

class Node{ int data; Node next; }

I tried many solutions but not creating an extra node screws things. Please help.

Here is the accompanying blog entry techieme.in/merging-two-sorted-singly-linked-list/

解决方案

Node MergeLists(Node list1, Node list2) { if (list1 == null) return list2; if (list2 == null) return list1; if (list1.data < list2.data) { list1.next = MergeLists(list1.next, list2); return list1; } else { list2.next = MergeLists(list2.next, list1); return list2; } }

更多推荐

专访:合并两个排序单链表

本文发布于:2023-11-29 02:41:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1644963.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:专访   链表   两个

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!