链表

反转一个单链表

  // 反转链表
  private ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        // q是反转后的链表
        ListNode q = reverseList(head.next);
        // head是当前节点
        head.next.next = head;
        head.next = null;
        return q;
    }

两两交换链表中的节点

// 此题是经典的递归题目,对于此类题目,需要自己手动画图,画图后思路会非常清晰。
// 非递归解法
public static ListNode swapPairs(ListNode head) {
        // 重新构造一个链表
        ListNode pre = new ListNode(0);
        pre.next = head;
        ListNode temp = pre;
        while (temp.next != null && temp.next.next != null) {
            ListNode p = temp.next;
            ListNode q = temp.next.next;
            p.next = q.next;
            temp.next = q;
            q.next = p;
            temp = p;
        }
        return pre.next;
    }

// 递归解法
public static ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode next = head.next;
        head.next = swapPairs1(next.next);
        next.next = head;
        return next;
    }

环形链表

// 快慢指针解法
public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        ListNode slow = head;
        ListNode fast = head.next;
        while (slow != fast) {
            // 这个if确保了每个节点都会判断一遍是否为空
            if (fast == null || fast.next == null) {
                return false;
            }
            slow = slow.next;
            fast = fast.next.next;
        }
        return true;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容