56 删除链表中重复的结点(重复的不保留)

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

public class Test56 {
    public ListNode deleteDuplication(ListNode pHead) {
        if (pHead == null || pHead.next == null) {
            return pHead;
        }
        ListNode head = new ListNode(-1);
        head.next = pHead;
        ListNode first = head;
        ListNode second = pHead;
        while (second != null) {
            if (second.next != null && second.val == second.next.val) {
                while (second.next != null && second.val == second.next.val) {
                    second = second.next;
                }
                first.next = second.next;
                second = first.next;
            } else {
                first = second;
                second = second.next;
            }
        }
        return head.next;
    }
}
好的,针对您的问题,以下是一个简单的 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` 函数来删除重复节点,最后再次打印链表来验证删除操作是否成功。 希望这个代码可以帮助您解决问题,如果您有任何疑问,请随时问我。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值