創(chuàng)建ListNode
public class ListNode {
int val; // 鏈表的值
ListNode next; // 下一個(gè)鏈表
public ListNode(int val) {
this.val = val;
}
}
1.給鏈表賦值:
ListNode l1= new ListNode(2);
2.從鏈表中取值:
ListNode l1= new ListNode(2);
int a = l1.val ;
經(jīng)典練習(xí)題:
2. 兩數(shù)相加
給你兩個(gè) 非空 的鏈表,表示兩個(gè)非負(fù)的整數(shù)。它們每位數(shù)字都是按照 逆序 的方式存儲(chǔ)的,并且每個(gè)節(jié)點(diǎn)只能存儲(chǔ) 一位 數(shù)字。
請(qǐng)你將兩個(gè)數(shù)相加,并以相同形式返回一個(gè)表示和的鏈表。
你可以假設(shè)除了數(shù)字 0 之外,這兩個(gè)數(shù)都不會(huì)以 0 開(kāi)頭。
輸入:l1 = [2,4,3], l2 = [5,6,4]
輸出:[7,0,8]
解釋?zhuān)?42 + 465 = 807.
題解樣例
public class TestListNode {
public static void main(String[] args) {
// 構(gòu)造第一個(gè)鏈表數(shù)值l1
ListNode l1 = new ListNode(2);
l1.next = new ListNode(4);
ListNode L2 = l1.next;
L2.next = new ListNode(3);
// 構(gòu)造第二個(gè)鏈表
ListNode l2 = new ListNode(5);
l2.next = new ListNode(6);
ListNode next = l2.next;
next.next = new ListNode(4);
ListNode listNode = addTwoNumbers(l1, l2);
System.out.println(listNode);
}
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode list = new ListNode(0); // 構(gòu)建鏈表
ListNode newList = list;
int carry = 0;
while (l1 != null || l2 != null) {
// 取值
int l1_1 = l1 != null ? l1.val : 0;
int l2_2 = l2 != null ? l2.val : 0;
int sum = carry + l1_1 + l2_2;
carry = sum / 10; // 計(jì)算carry
newList.next = new ListNode(sum % 10); // 為下一個(gè)節(jié)點(diǎn)賦值
newList = newList.next; // 指針移動(dòng)到下一個(gè)節(jié)點(diǎn)
if (l1 != null) {
l1 = l1.next;
}
if (l2 != null) {
l2 = l2.next;
}
}
if (carry > 0) {
newList.next = new ListNode(carry);
}
return list.next;
}
}
每天進(jìn)步一點(diǎn)點(diǎn)~