关于java:LeetCode083删除排序链表中的重复元素

6次阅读

共计 1184 个字符,预计需要花费 3 分钟才能阅读完成。

删除排序链表中的反复元素

题目形容:存在一个按升序排列的链表,给你这个链表的头节点 head,请你删除所有反复的元素,使每个元素 只呈现一次。

返回同样按升序排列的后果链表。

示例阐明请见 LeetCode 官网。

起源:力扣(LeetCode)
链接:https://leetcode-cn.com/probl…
著作权归领扣网络所有。商业转载请分割官网受权,非商业转载请注明出处。

解法一:链表遍历
  • 首先,如果 head 为 null 或者 head 只有一个结点,间接返回 head;
  • 否则,从第二个结点开始遍历,记录以后结点为 cur,以后的不反复的值为 curVal,如果下一个结点的值等于 curVal,则跳过这个结点,持续遍历下一个结点 next,如果下一个结点的值不等有 curVal,则更新 curVal 的值为下一个结点的值,且 cur 的下一个节点设置为 next,晓得遍历实现为为止,最初返回 head。
public class LeetCode_083 {public static ListNode deleteDuplicates(ListNode head) {if (head == null || head.next == null) {return head;}
        ListNode next = head.next, cur = head;
        int curVal = head.val;
        while (next != null) {if (next.val == curVal) {
                next = next.next;
                cur.next = null;
            } else {
                cur.next = next;
                cur = cur.next;
                curVal = next.val;
                next = next.next;
            }
        }
        return head;
    }

    public static void main(String[] args) {ListNode root = new ListNode(1);
        root.next = new ListNode(1);
        root.next.next = new ListNode(2);
        root.next.next.next = new ListNode(3);
        root.next.next.next.next = new ListNode(3);
        System.out.println("===== 解决前 =====");
        ListNode temp = root;
        while (temp != null) {System.out.print(temp.val + " ");
            temp = temp.next;
        }
        System.out.println();

        deleteDuplicates(root);
        System.out.println("===== 解决后 =====");
        while (root != null) {System.out.print(root.val + " ");
            root = root.next;
        }
    }
}

【每日寄语】 但愿这漫长渺小人生,不负你每个光芒时候。

正文完
 0