1.两个链表生成相加链表
注意用到栈结构,不需要单独算出每一个链表代表的数字
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) {
// write code here
Stack<Integer> s1=new Stack<>();
Stack<Integer> s2=new Stack<>();
ListNode i=head1;
while(i!=null){
s1.push(i.val);
i=i.next;
}
i=head2;
while(i!=null){
s2.push(i.val);
i=i.next;
}
int tmp=0;
ListNode res=null;
while(!s1.isEmpty() || !s2.isEmpty()){
int a=s1.isEmpty()?0:s1.pop();
int b=s2.isEmpty()?0:s2.pop();
int sum=a+b+tmp;
tmp=sum/10;
ListNode p=new ListNode(sum%10);
p.next=res;
res=p;
}
if(tmp>0){
ListNode p=new ListNode(tmp);
p.next=res;
res=p;
}
return res;
}
}
2.判断链表是否有环
注意:循环条件为快指针和快指针的next——防止引起空指针异常
快指针一次走两步
public class Solution {
public boolean hasCycle(ListNode head) {
if(head==null|| head.next==null) return false;
ListNode i=head,j=head;
while(j!=null && j.next!=null){
i=i.next;
j=j.next.next;
if(i==j) return true;
}
return false;
}
}
3.链表中环的入口结点
注:快指针第二遍遍历链表时速度要放慢了
public class Solution {
public ListNode EntryNodeOfLoop(ListNode pHead) {
ListNode i=pHead,j=pHead;
boolean flag=false;
while(j!=null && j.next!=null){
i=i.next;
j=j.next.next;
if(i==j){
flag=true;
break;
}
}
if(!flag) return null;
j=pHead;
while(i!=j){
i=i.next;
j=j.next;
}
return j;
}
}
4.合并有序链表
public class Solution {
public ListNode mergeTwoLists (ListNode l1, ListNode l2) {
// write code here
if(l1==null) return l2;
if(l2==null) return l1;
ListNode p=new ListNode(0);
ListNode res=p;
ListNode a=l1,b=l2;
while(a!=null && b!=null){
if(a.val<=b.val){
p.next=a;
p=p.next;
a=a.next;
}
else{
p.next=b;
p=p.next;
b=b.next;
}
}
p.next=(a==null)?b:a;
return res.next;
}
}
5. 两个链表的第一个公共结点
双指针:每个指针都走两条链表
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
ListNode i=pHead1,j=pHead2;
while(i!=j){
i=i!=null?i.next:pHead2;
j=j!=null?j.next:pHead1;
}
return i;
}
}