剑指Offer

1.2 链表(5)(需要双指针解决纯链表问题)

2017-12-27  本文已影响13人  coderjiege

套路


注意点


目录


链表中倒数第k个结点

输入一个链表,输出该链表中倒数第k个结点。

public ListNode FindKthToTail(ListNode head,int k) {
    if (head == null || k < 1) {
        return null;
    }
    ListNode front = head, behind = head;
    for (int i = 0; i < k - 1; i++) {
        front = front.next;
        if (front == null) {
            return null;
        }
    }
    while (front.next != null) {
        front = front.next;
        behind = behind.next;
    }
    return behind;
}

反转链表

输入一个链表,反转链表后,输出链表的所有元素。

public ListNode ReverseList(ListNode head) {
    if (head == null) {
        return null;
    }
    ListNode prev = null;
    while (head.next != null) {
        ListNode next = head.next;
        head.next = prev;
        prev = head;
        head = next;
    }
    head.next = prev;
    return head;
}

两个链表的第一个公共结点

输入两个链表,找出它们的第一个公共结点。

public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
    if (pHead1 == null || pHead2 == null) {
        return null;
    }
    ListNode p1 = pHead1, p2 = pHead2;
    while (p1 != p2) {
        p1 = p1 == null ? p1 = pHead2 : p1.next;
        p2 = p2 == null ? p2 = pHead1 : p2.next;
    }
    return p1;
}

链表中环的入口结点

一个链表中包含环,请找出该链表的环的入口结点。

public ListNode EntryNodeOfLoop(ListNode pHead) {
    if (pHead == null) {
        return null;
    }
    ListNode fast = pHead, slow = pHead;
    while (fast.next != null && fast.next.next != null) {
        fast = fast.next.next;
        slow = slow.next;
        if (fast == slow) {
            fast = pHead;
            while (fast != slow) {
                fast = fast.next;
                slow = slow.next;
            }
            return fast;
        }
    }
    return null;
}

删除链表中重复的结点

在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5

public ListNode deleteDuplication(ListNode pHead) {
    if (pHead == null) {
        return null;
    }
    ListNode front = new ListNode(-1);
    front.next = pHead;
    ListNode pre = front, cur = front;
    int last = pre.val;
    while (cur.next != null) {
        cur = cur.next;
        if (last != cur.val) {
            if (cur.next == null || cur.val != cur.next.val) {
                pre.next = cur;
                pre = cur;
            }
            last = cur.val;
        }
    }
    pre.next = null;
    return front.next;
}

上一篇下一篇

猜你喜欢

热点阅读