兩個連結串列生成相加連結串列
阿新 • • 發佈:2021-01-26
題目描述
假設連結串列中每一個節點的值都在 0 - 9 之間,那麼連結串列整體就可以代表一個整數。
給定兩個這種連結串列,請生成代表兩個整數相加值的結果連結串列。
連結串列 1 為 9->3->7,連結串列 2 為 6->3,最後生成新的結果連結串列為 1->0->0->0。
示例
輸入:(6 -> 1 -> 7) + (2 -> 9 -> 5),即617 + 295
輸出:9 -> 1 -> 2,即912
解決方法
- 反轉兩個連結串列
- 同時遍歷兩個連結串列,依次相加生成新節點,並記錄進位
- 反轉新連結串列
==> 還可以簡單進階一下,不完全生成一條全新的連結串列。也就是說在任選一條連結串列基礎上賦值結果,若判斷少了節點,再新建,並直接連線在該連結串列後
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head1 ListNode類
* @param head2 ListNode類
* @return ListNode類
*/
public ListNode addInList (ListNode head1, ListNode head2) {
if (head1 == null || head2 == null) {
return head1 == null ? head2 : head1;
}
head1 = reverse(head1);
head2 = reverse(head2);
ListNode ptail = new ListNode(-1);
ListNode phead = ptail, pnew = ptail;
int temp = 0; //進位
while (head1 != null || head2 != null || temp > 0) {
int num1 = (head1 == null ? 0 : head1.val);
int num2 = (head2 == null ? 0 : head2.val);
int num = num1 + num2 + temp;
pnew = new ListNode(num%10);
ptail.next = pnew;
ptail = ptail.next;
temp = num/10;
head1 = (head1 == null ? null : head1.next);
head2 = (head2 == null ? null : head2.next);
}
phead = reverse(phead.next);
return phead;
}
public ListNode reverse (ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode preNode = head;
ListNode target = head.next;
while (target != null) {
preNode.next = target.next;
target.next = head;
head = target;
target = preNode.next;
}
return head;
}
}
進階
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head1 ListNode類
* @param head2 ListNode類
* @return ListNode類
*/
public ListNode addInList (ListNode head1, ListNode head2) {
if (head1 == null || head2 == null) {
return head1 == null ? head2 : head1;
}
ListNode ptail = head2; //定位尾結點
head1 = reverse(head1);
head2 = reverse(head2);
ListNode phead = head2;
int temp = 0; //進位
while (head1 != null || head2 != null || temp > 0) {
int num1 = (head1 == null ? 0 : head1.val);
int num2 = (head2 == null ? 0 : head2.val);
int num = num1 + num2 + temp;
if (head2 != null) {
head2.val = num%10;
} else {
ptail.next = new ListNode(num%10);
ptail = ptail.next;
}
temp = num/10;
head1 = (head1 == null ? null : head1.next);
head2 = (head2 == null ? null : head2.next);
}
phead = reverse(phead);
return phead;
}
public ListNode reverse (ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode preNode = head;
ListNode target = head.next;
while (target != null) {
preNode.next = target.next;
target.next = head;
head = target;
target = preNode.next;
}
return head;
}
}