欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

【链表】18题-删除链表中重复的节点

程序员文章站 2022-06-19 12:13:48
1 题目描述在一个排序的链表中,存在着重复的节点,请删除该链表中重复的节点,重复的节点不保留,返回链表头指针示例: 输入:1 -> 2 -> 2 -> 3 -> 3 -> 4 -> 5 输出:1 -> 4 -> 52 解题思路遍历节点的同时判断当前节点与下一个节点是否相同,如果相同则删除。package section5_5;public class Solution { private static class ListNode...

1 题目描述

在一个排序的链表中,存在着重复的节点,请删除该链表中重复的节点,重复的节点不保留,返回链表头指针

示例:

 输入:1 -> 2 -> 2 -> 3 -> 3 -> 4 -> 5
 输出:1 -> 4 -> 5

2 解题思路

遍历节点的同时判断当前节点与下一个节点是否相同,如果相同则删除。

package section5_5;

public class Solution {

    private static class ListNode {
        int val;
        ListNode next;
        ListNode(int x) { val = x; }
    }

    public ListNode deleteDuplication(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode first = new ListNode(-1);
        first.next = head;
        ListNode cur = head;
        ListNode preNode = first;
        while (cur != null && cur.next != null) {
            if (cur.val == cur.next.val) {
                int val = cur.val;
                while (cur != null && cur.val == val) {
                    cur = cur.next;
                }
                preNode.next = cur;
            }
            else {
                preNode = cur;
                cur = cur.next;
            }
        }
        return first.next;
    }

    //测试用例
    public static void main(String[] args) {
        ListNode node = new ListNode(1);
        int[] data = {2,2,3,3,4,5};
        ListNode head = node;
        for (int i = 1;i < 7;i++) {
            node.next = new ListNode(data[i-1]);
            node = node.next;
        }
        node = head;
        while (node != null) {
            System.out.print(node.val + " ");
            node = node.next;
        }
        System.out.println();

        Solution solution = new Solution();
        node = solution.deleteDuplication(head);
        while (node != null) {
            System.out.print(node.val + " ");
            node = node.next;
        }
    }

}

【链表】18题-删除链表中重复的节点

本文地址:https://blog.csdn.net/qq_41242680/article/details/111993545