单链表删除相同元素

单一链表删除相同元素

#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
    int Data;
    struct Node *next;
}LNode,*PLNode;
void CreateLink(PLNode *L,int n)
{
    int i;
    *L=(PLNode)malloc(sizeof(LNode));   //创立空间很重要
    PLNode p=*L;
    p->next=NULL;
    PLNode s;
    for(i=0;i<n;i++)
    {
        s=(PLNode)malloc(sizeof(LNode));
        scanf("%d",&(s->Data));
        p->next=s;
        p=s;
    }
    p->next=NULL;
    return ;
}
void Del(PLNode L1)   //头指针方便了链表的操作 用头的next表示下一元素,而不是取当前的data
{
    PLNode p,q;      //这些点都是指针变量
    p=L1;
    while(p->next!=NULL)
    {
        q=p->next;
        while(q->next!=NULL)
        {
            if(p->next->Data==q->next->Data)
            {
                 q->next=q->next->next;
            }
            else
            q=q->next;
        }
        p=p->next;
    }
}
void Print(PLNode L1)
{
    PLNode head=L1;
    while(head->next)
    {
        if(head->next->next==NULL)
        printf("%d\n",head->next->Data);
        else
        printf("%d ",head->next->Data);   //链表最后不输空格的方法
        head=head->next;
    }
}
int main()
{
    PLNode L;
    int n;
    scanf("%d",&n);
    CreateLink(&L,n);
    Del(L);
    Print(L);
    return 0;
}

 

删除单链表中所有相同元素的C++实现通常涉及遍历链表和使用指针技巧。这里是一个简单的示例: ```cpp #include <iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; ListNode* deleteDuplicates(ListNode* head) { if (head == nullptr || head->next == nullptr) { return head; // 如果链表只有一个节点或为空,直接返回 } ListNode dummy(0); // 创建虚拟头节点,避免处理边界条件 dummy.next = head; ListNode* current = &dummy; while (current->next != nullptr && current->next->next != nullptr) { if (current->next->val == current->next->next->val) { current->next = current->next->next; } else { current = current->next; } } return dummy.next; // 返回去除了重复元素的新链表头节点 } // 测试函数 void printList(ListNode* node) { while (node != nullptr) { cout << node->val << " "; node = node->next; } cout << endl; } int main() { ListNode* list = new ListNode(1); list->next = new ListNode(2); list->next->next = new ListNode(2); list->next->next->next = new ListNode(3); list->next->next->next->next = new ListNode(4); cout << "Original List: "; printList(list); list = deleteDuplicates(list); cout << "List after removing duplicates: "; printList(list); return 0; } ``` 在这个代码里,我们创建了一个`deleteDuplicates`函数,它会遍历链表并删除连续的重复值。如果遇到相同的值,就跳过下一个节点。最后返回新链表的头节点。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值