目录
- 题目:
- 解析:
- 方法:
- 代码:
- 链表常用技巧:
题目:
链接: link
解析:
方法:
代码:
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val = val; }* ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/
class Solution {public ListNode addTwoNumbers(ListNode l1, ListNode l2) {//创建虚拟头节点返回结果:ListNode cur1 = l1, cur2 = l2;ListNode newhead = new ListNode(0);int t = 0;//用来尾插操作的指针ListNode prev = newhead;while(cur1 != null || cur2 != null || t != 0){//先加第一个链表if(cur1 != null){t += cur1.val;cur1 = cur1.next;}//先加第二个链表if(cur2 != null){t += cur2.val;cur2 = cur2.next;}//把t尾插到虚拟头节点prev.next = new ListNode(t%10);//去t的个位创建新节点t /= 10;prev = prev.next;}return newhead.next;}
}
链表常用技巧:
1.可以创建虚拟头节点来进行最后的返回,因为题目的第一个节点一般都存有数据
2.创建新的引用来进行变量,来进行头插和尾插