java链表
在java中要自定义一个链表类
class ListNode{
int val;
ListNode next;
ListNOde(int x) {val = x;}
}
题目1:从未到头打印一个链表。
方法:递归法先递推至链表末端,回溯时,依次将节点加入列表。
终止条件:head==None。
递推:访问下一个节点head.next;
回溯:将head.val加入列表。
class Solution {
ArrayList<Integer> tmp = new ArrayList<Integer>();
public int[] reversePrint(ListNode head) {
recur(head);
int[] res = new int[tmp.size()];
for(int i = 0; i < res.length; i++)
res[i] = tmp.get(i);
return res;
}
void recur(ListNode head) {
if(head == null) return;
recur(head.next);
tmp.add(head.val);
}
}
题目2
将两个链表数加起来:每个节点只存储一位数字,逆序存储。
如:7->2->3
2->8->2
输出:8->0->6
思路:定位输出从头节点开始两两相加,再把值存入新的链表 节点,满10就进位。
要点:创建一个新链表存储数据,判断进位当最后一个数字大于10需要进位需要再创建一个新节点。
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = null, tail = null;//创建两个链表节点为空
int carry = 0;//用来进位
while (l1 != null || l2 != null) {
int n1 = l1 != null ? l1.val : 0;
int n2 = l2 != null ? l2.val : 0;
int sum = n1 + n2 + carry;//把两节点的值相加
if (head == null) {
head = tail = new ListNode(sum % 10);//head储存tail的头节点数据方便访问数据
} else {
tail.next = new ListNode(sum % 10);
tail = tail.next;//用tail去建立链表
}
carry = sum / 10;
if (l1 != null) {
l1 = l1.next;
}
if (l2 != null) {
l2 = l2.next;
}
}
if (carry > 0) {
tail.next = new ListNode(carry);//判断最后一位是否需要进位
}
return head;
}