<JAVA>常见链表题目总结(一)

链表作为常考算法题,十分基础又十分重要。
因此,Moon在此对于常见链表题目进行总结,并给出解法。

Leetcode题目序号主要思路解法
206反转链表双指针
141环形链表(判断是否有环)快慢指针
142环形链表(二)(找第一个入口节点)快慢指针
160相交链表(找相交节点)双指针
21 合并两个有序链表1.递归 2.双指针+假想节点
206 反转链表
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;
		}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值