1.给定排序的链表,删除重复元素,只保留重复元素第一次出现的结点。
(1)代码:
# include <iostream>
using namespace std;
//定义节点结构
typedef struct snode
{
int data;
snode *pnext;
snode(int value)
:data(value), pnext(NULL)
{}
}Node;
//声明函数
void OutLink(Node *pHead);
void Destroy(Node *P);
void DelSame(Node *Head);
//输出链表
void OutLink(Node *pHead)
{
//注意判断指针是否为空
if (pHead == NULL)
{
cout << "链表为空";
}
Node *pCur = pHead->pnext;
while (pCur != NULL)
{
cout << "->" << pCur->data;
pCur = pCur->pnext;
}
cout << endl;
}
//删除指针
void Destroy(Node *P)
{
Node *next;
if (P != NULL)
{
next = P->pnext;
delete P;
P = next;
}
}
//删除重复
void DelSame(Node *Head)
{
Node *Now = Head->pnext;
Node *Next;
while (Now)
{
Next = Now->pnext;
if (Next && (Now->data == Next->data))
{
Now->pnext = Next->pnext;
delete Next;
}
else
{
Now = Next;
}
}
}
//主函数
int main()
{
Node *Head = new Node(0);
Node *Next = Head;
int array[13] = { 1,2,2,3,4,4,4,5,6,6,