链表作为常考算法题,十分基础又十分重要。
因此,Moon在此对于常见链表题目进行总结,并给出解法。
Leetcode题目序号 | 主要思路解法 |
206反转链表 | 双指针 |
141环形链表(判断是否有环) | 快慢指针 |
142环形链表(二)(找第一个入口节点) | 快慢指针 |
160相交链表(找相交节点) | 双指针 |
21 合并两个有序链表 | 1.递归 2.双指针+假想节点 |
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode cur = head;
while(cur!=null){
ListNode nexttemp = cur.next;
cur.next = pre;
pre = cur;
cur = nexttemp;
}return pre;
}
}
141 环形链表
public class Solution {
public boolean hasCycle(ListNode head) {
if(head==null||head.next==null)return false;
ListNode fast =head;
ListNode slow =head;
while(fast!=slow){
if(fast==null||fast.next==null)return false;
fast = fast.next.next;
slow = slow.next;
}return true;
}
}
142 环形链表(二)
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while(true){
if(fast==null||fast.next==null)return null;
fast = fast.next.next;
slow = slow.next;
if(fast==slow)break;//当第一次相遇跳出
}
fast = head;
//将快指针重新放到开始,与慢指针一起走,必定相遇!
while(fast!=slow){
fast = fast.next;
slow = slow.next;
}return fast;
}
}
160 相交链表
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) return null;
ListNode pA = headA, pB = headB;
while(pA != pB){
pA = pA == null ? headB : pA.next;
pB = pB == null ? headA: pB.next;
}
return pA;
}
}
21 合并两个有序链表
解法一:
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null)return l2;
if(l2 == null)return l1;
ListNode dum = new ListNode(0);
ListNode cur = dum;
while(l1!=null&&l2!=null){
if(l1.val < l2.val){
cur.next = l1;
l1 = l1.next;
}else{
cur.next = l2;
l2 = l2.next;
}
cur = cur.next;
}
cur.next = l1!=null?l1:l2;
return dum.next;
}
}
解法二:
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;
}