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

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;
        }
    }

}

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值