目录
题目一:两个有序链表的合并
给定两个有序链表的头节点head1和head2,
返回合并之后的大链表,要求依然有序
例子1-> 3-> 3-> 5-> 7 2 -> 2-> 3->3->7
返回1->2->2->3-> 3-> 3-> 3->5->7
思路:
- 确认头节点head;
- 用指针cur1和cur2分别跟随两个链表;
- 另一个头指针pre指向cur1和cur2中较小的那个,然后cur(较小)和pre后移(next);
public static Node mergeOrderList (Node head1, Node head2) {
if (head1 == null || head2 == null) {
return head1 == null ? head2 : head1;
}
Node head = head1.value <= head2.value ? head1 :head2;
Node cur1 = head.next;
Node cur2 = head == head1 ? head2 :head1;
Node pre = head;
while (cur1 != null && cur2 != null) {
if (cur1.value <= cur2.value) {
pre.next = cur1;
cur1 = cur1.next;
} else {
pre.next = cur2;
cur2 = cur2.next;
}
pre = pre.next;
}
pre.next = cur1 == null ? cur2 :cur1;
return head;
}
测试
public static void main(String[] args) {
Node n1 = new Node(2);
n1.next = new Node(4);
n1.next.next = new Node(11);
Node n2 = new Node(1);
n2.next = new Node(3);
n2.next.next = new Node(5);
Node n3 = mergeOrderList(n1,n2);
while (n3 != null) {
System.out.print(n3.value+" ");
n3 = n3.next;
}
输出
1 2 3 4 5 11
题目二:链表相加
给定两个链表的头节点head1和head2,
认为从左到右是某个数字从低位到高位,返回相加之后的链表
例子 4->3->62-> 5-> 3
返回 6-> 8 -> 9
解释 634+ 352 = 986
思路:
- 记录进位carry,本位curNum
- 以较短链表为基准
- 以较长链表的剩余部分为基准
- 当两个链表都遍历结束时,判断最后是否有一个进位
//计算链表长度
public static int Length (Node head) {
if (head == null) {
return 0;
}
int length = 0;
while (head != null) {
length++;
head = head.next;
}
return length;
}
//主方法
public static Node AddList (Node head1, Node head2) {
if (head1 == null || head2 == null) {
return head1 == null ? head2 : head1;
}
Node l = Length(head1) >= Length(head2) ? head1 :head2;
Node s = l.value== head1.value ? head2 :head1;
Node head = l;
int carry = 0;
int curNum = 0;
Node lastNode = null;
while (s != null) {
curNum = s.value + l.value + carry;
l.value = curNum % 10;
carry = curNum / 10;
lastNode = l;
l = l.next;
s = s.next;
}
while (l != null) {
curNum = l.value + carry;
l.value = curNum % 10;
carry = curNum / 10;
lastNode = l;
l = l.next;
}
if (carry != 0) {
lastNode.next = new Node(1);
}
return head;
}
测试
public static void main(String[] args) {
Node n1 = new Node(2);
n1.next = new Node(4);
n1.next.next = new Node(8);
Node n2 = new Node(1);
n2.next = new Node(3);
n2.next.next = new Node(5);
Node n4 = null;
Node n3 = AddList(n1,n2);
while (n3 != null) {
System.out.print(n3.value+" ");
n3 = n3.next;
}
}
输出
3 7 3 1