[C++]链表中删除连续重复出现的结点

// DeleteDuplicateNode.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <cstdlib>
#include <iostream>
using std::cout;
using std::endl;

typedef struct SNode {
    int value;
    SNode * pNext;
    SNode(int v):value(v),pNext(NULL){}
}SNode;

void Print(SNode* head) {
    SNode* p = head->pNext;
    while (p)
    {
        cout << p->value;
        p = p->pNext;
        if (p)
            cout << "->";
    }
    cout << endl;
}

void Delete(SNode* head) {
    while (head)
    {
        SNode* t = head;
        head = head->pNext;
        delete t;
    }
}

void DeleteDuplicateNode(SNode* head) {
    SNode* p = head->pNext;
    SNode* p1 = p;
    p = p->pNext;
    while(p)
    {
        if (p1->value == p->value) {
            SNode* temp = p;
            p = p->pNext;
            p1->pNext = p;
            delete temp;
        }
        else {
            p1 = p;
            p = p->pNext;
        }
    }
}

int main()
{
    SNode* head = new SNode(0);
    for (int i = 0; i < 15; i++) {
        SNode* p = new SNode(rand() % 6);
        p->pNext = head->pNext;
        head->pNext = p;
    }
    cout << "Before:\t";
    Print(head);
    DeleteDuplicateNode(head);
    cout << "After:\t";
    Print(head);
    Delete(head);
    system("pause");
    return 0;
}

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值