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

一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。
在这里插入图片描述

public ListNode deleteDuplication() {
    if (this.head == null) {
        return null;
    }
    ListNode cur = this.head;
    ListNode newHead = new ListNode(-1);
    ListNode temp = newHead;
    while (cur != null) {
        //重复的节点
        if (cur.next != null && cur.data == cur.next.data) {
            //每一次重复都需要判断cur.next
            while (cur.next != null && cur.data == cur.next.data) {
                cur = cur.next;
            }
            //两个重复点相邻时
            cur = cur.next;
        } else {
            temp.next = cur;
            temp = temp.next;
            cur = cur.next;
        }
    }
    temp.next = null;//最后一个结点也是重复的,需要将temp.next置为空
    return newHead.next;
}

public void display(ListNode newHead) { //要从新的头开始打印,需要接受newHead
    if (newHead == null) {
        return;
    }
    ListNode cur = newHead;
    while (cur != null) {
        System.out.print(cur.data + " ");
        cur = cur.next;
    }
    System.out.println();
    }
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,针对您的问题,以下是一个简单的 C 语言链表删除重复结点保留一个的实现方法: ```c #include <stdio.h> #include <stdlib.h> struct node { int data; struct node* next; }; void delete_duplicate(struct node* head) { struct node *current, *runner, *duplicate; current = head; while (current != NULL && current->next != NULL) { runner = current; while (runner->next != NULL) { if (current->data == runner->next->data) { duplicate = runner->next; runner->next = runner->next->next; free(duplicate); } else { runner = runner->next; } } current = current->next; } } void print_list(struct node* head) { while (head != NULL) { printf("%d ", head->data); head = head->next; } printf("\n"); } int main() { struct node* head = NULL; struct node* second = NULL; struct node* third = NULL; head = (struct node*) malloc(sizeof(struct node)); second = (struct node*) malloc(sizeof(struct node)); third = (struct node*) malloc(sizeof(struct node)); head->data = 1; head->next = second; second->data = 3; second->next = third; third->data = 3; third->next = NULL; printf("Original list: "); print_list(head); delete_duplicate(head); printf("List with duplicates removed: "); print_list(head); return 0; } ``` 在上面的代码,我们首先定义了一个结构体 `node` 来表示链表节点,其包含了一个整型数据 `data` 和一个指向下一个节点的指针 `next`。接着实现了一个 `delete_duplicate` 函数,它使用两个指针 `current` 和 `runner` 分别指向当前节点和当前节点之后的节点,并且在内部使用了一个 `duplicate` 指针来删除重复节点。最后,我们定义了一个 `print_list` 函数来打印链表的所有节点。 在 `main` 函数,我们创建了一个简单的链表,其包含三个节点,其第二个和第三个节点的数据相同。我们首先打印出原始的链表,然后调用 `delete_duplicate` 函数来删除重复节点,最后再次打印链表来验证删除操作是否成功。 希望这个代码可以帮助您解决问题,如果您有任何疑问,随时问我。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值