21. Merge Two Sorted Lists
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode res=new ListNode(0);
ListNode p=res;
while(l1!=null&&l2!=null){
if(l1.val<=l2.val){
p.next=l1;
l1=l1.next;
}
else{
p.next=l2;
l2=l2.next;
}
p=p.next;
}
if(l1!=null){
p.next=l1;
}
if(l2!=null){
p.next=l2;
}
return res.next;
}
}
使用recursion:
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null){
return l2;
}
if(l2==null){
return l1;
}
if(l1.val<=l2.val){
l1.next=mergeTwoLists(l1.next,l2);
return l1;
}
else{
l2.next=mergeTwoLists(l1,l2.next);
return l2;
}
}
}
141. Linked List Cycle
判断linkedlist里面是否有环,使用two pointer。
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode faster=head;
ListNode slower=head;
while(faster!=null&&faster.next!=null){
faster=faster.next.next;
slower=slower.next;
if(faster==slower){
return true;
}
}
return false;
}
}
2. add two numbers
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse orderand each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
PS:当9999..时可以不断进位
用recursion,把短的linkedlist用0补全,多用O(n)的space。
class Solution {
private ListNode addTwoNumbers(ListNode l1,ListNode l2, int carry){
if(l1==null&&l2==null){
if(carry==0){
return null;
}
return new ListNode(1);
}
if(l1==null){
l1=new ListNode(0);
}
if(l2==null){
l2=new ListNode(0);
}
int nCarry=0;
int sum= l1.val+l2.val+carry;
if(sum>=10){
sum=sum-10;
nCarry=1;
}
l1.val=sum;
l1.next=addTwoNumbers(l1.next,l2.next,nCarry);
return l1;
}
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
return addTwoNumbers(l1,l2,0);
}
}
这种方法 直接修改了input,这种习惯不好。
不用recursion比较好。
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head=new ListNode(0);
ListNode p=head;
int c=0;
int sum=0;
while(l1!=null||l2!=null){
int add1=0;
int add2=0;
if(l1!=null){
add1=l1.val;
l1=l1.next;
}
if(l2!=null){
add2=l2.val;
l2=l2.next;
}
sum=(add1+add2+c)%10;
c=(add1+add2+c)/10;
p.next=new ListNode(sum);
p=p.next;
}
if(c!=0){
p.next=new ListNode(1);
}
return head.next;
}
}