题目如下:
将两个有序链表合并为一个有序链表,不允许使用额外的内存空间
思路:
(使用java语言)循环实现——>
(1)创建两个链表:链表1和链表2;在合并链表的方法里让链表1的头节点为head1,链表2的头节点为head2
(2)先进行判空,链表1、链表2为空时,执行return;设置两个游标cur1、cur2分别指向两个链表的头节点;设置游标指向的新链表的头newHead和尾newTail
(3)设置while循环,当cur1和cur2指向都不为空时执行循环;
(4)判断cur1和cur2指向的节点的值;cur1小则先判断新链表是否为空;新链表为空就让newHead指向cur1指向的节点,newTail指向cur1指向的节点,cur1向后移动一位;新链表不为空就让newTail.next指向cur1,newTail向后移动一位,cur1向后移动一位;
(5)cur2小则先判断新链表是否为空;新链表为空就让newHead指向cur2指向的节点,newTail指向cur2指向的节点,cur2向后移动一位;新链表不为空就让newTail.next指向cur2,newTail向后移动一位,cur2向后移动一位;
(6)循环终止之后,判断cur1和cur2哪个指向为空,cur1指向为空,就把cur2链接到新链表的尾部;cur2指向为空,就把cur1链接到新链表的尾部;
(7)输出新链表。
思路图示:
代码如下:
public class Test1 {
ListNode head = null;
public static void main(String[] args){
Test1 linkList1 = new Test1();//链表1
Test1 linkList2 = new Test1();//链表2
linkList1.insert(1);
linkList1.insert(3);
linkList1.insert(5);
linkList1.insert(7);
linkList1.printLink();//打印链表1
System.out.println("******************************");
linkList2.insert(2);
linkList2.insert(4);
linkList2.insert(6);
linkList2.printLink();//打印链表2
System.out.println("******************************");
conflateList(linkList1.head,linkList2.head);
}
//将两个有序链表合并为一个新的有序链表(升序为例)
public static ListNode conflateList(ListNode head1,ListNode head2) {
//先进行判空,链表1、链表2为空时,执行return
if (head1 == null) {
return head2;
}
if (head2 == null) {
return head1;
}
//设置两个游标分别指向两个链表
ListNode cur1 = head1;
ListNode cur2 = head2;
//设置游标指向的新链表的头和尾
ListNode newHead = null;
ListNode newTail = null;
//两个链表任何一个为空循环就终止
while (cur1 != null && cur2 != null) {
if (cur1.value <= cur2.value) {//当cur1的值小或两者相等时
if (newHead == null) {
//当新链表为空时
newHead = cur1;//newHead指向新链表的头节点
newTail = cur1;//newTail指向新链表的尾节点
cur1 = cur1.next;//cur1向后移动一位
}else {
//新链表不为空时
newTail.next = cur1;//newTail.next指向cur1节点
newTail = newTail.next;//newTail向后移动一位
cur1 = cur1.next;//cur1向后移动一位
}
} else {//当cur2的值小或两者相等时
if (newHead == null) {
//当新链表为空时
newHead = cur2;//newHead指向新链表的头节点
newTail = cur2;//newTail指向新链表的尾节点
cur2 = cur2.next;//cur2向后移动一位
}else {
newTail.next = cur2;//newTail.next指向cur2节点
newTail = newTail.next;//newTail向后移动一位
cur2 = cur2.next;//cur2向后移动一位
}
}
}
//循环终止之后 把还剩有节点的链表并到新链表尾部即可
if (cur1 == null) {//cur1为空
newTail.next = cur2;//cur2链接到尾部
} else {//cur2为空
newTail.next = cur1;//cur2链接到尾部
}
System.out.println(newHead);
return newHead;
}
// 尾插法
public void insert(int value) {
// 创建节点
ListNode newNode = new ListNode(value);
// 生成链表
// 1.判断链表记录器有没有值
if (head == null) {
head = newNode;
return;
}
// 链表记录器有值
ListNode indexNode = head;
while (indexNode.next != null) {
indexNode = indexNode.next;
}
indexNode.next = newNode;
}
// 链表的输出
public void printLink() {
ListNode indexNode = head;
while (indexNode != null) {
System.out.println(indexNode.value);
indexNode = indexNode.next;
}
}
}
节点类:
public class ListNode {//节点类
int value; //数值域
ListNode next; //节点域
//定义一个构造函数
public ListNode(int value) {
this.value = value;
}
//toString方法
@Override
public String toString() {
return "ListNode{" +
"value=" + value +
", next=" + next +
'}';
}
}