您的位置:首页 > 其它

无头单链表删除随机节点

2015-10-19 23:01 316 查看
#include<iostream>

#include<string>

#include<iterator>

using namespace std;

//  从无头单链表中删除节点

//  假设一个没有头指针的单链表,一个指针指向此单链表中间的一个节点(不是第一个也不是最后一个节点),请将该结点从单链表中删除

//  创建节点

typedef struct  node

{
int data;
struct node *next;

}Node;

//  创建链表

struct  node*createList(struct  node*);

//  输出链表

void printList(struct  node*);

//  删除随机链表中的结点

void deleteRondomNode(struct  node*);

//  释放内存

void freeMemory(struct  node*);

int main()

{
struct  node* head=NULL;
head=createList(head);
printList(head);
//  链表中至少含有四个数据
Node *rondomNode=head->next->next;      //  我们假设删除第三个节点    deleteRondomNode这个函数里面只有一个指针,没有head指针
deleteRondomNode(rondomNode);      //  注意:这里head只是进行输出标记,处理的时候并没有使用到它
printList(head);

freeMemory(head);        //  释放内存   这一步不能省略   new分配空间在堆区,不能自动释放
system("pause");
return 0;

}

//  创建链表

struct  node*createList(struct  node*head)

{
struct  node *p=nullptr,*q=nullptr;
unsigned int ival;
cout<<"Input  integers:"<<endl;     //  输入非整数结束循环
while (cin>>ival)
{
p=new Node;
p->data=ival;       
p->next=nullptr;         //  分配内存空间,给p赋值
if(head==NULL)
head=q=p;
else
{
q->next=p;
q=q->next;
}
}
return head;

}

//  删除随机链表中的结点    不能借助头指针    头指针的作用只是输出的时候看下结点是否被删除

void deleteRondomNode(Node *pCurrent)

{
if(pCurrent==nullptr)          // p不符合题意
return;
else
{
Node *qNext=pCurrent->next;   
if(qNext==nullptr)      //  p为最后一个节点,不符合题意
return;
else
{
pCurrent->data=qNext->data;      //  狸猫换太子的做法
pCurrent->next=qNext->next;
delete qNext;
}
}

}

//  输出链表

void printList(struct  node *head)

{
Node *p=head;

cout<<"链表输出数据:"<<endl;   
while (p!=NULL)
{
cout<<p->data<<"   ";
p=p->next;
}
cout<<endl;

}

//  释放内存

void freeMemory(struct  node *head)

{
Node *p;
while (head!=nullptr)
{
p=head->next;
delete head;
head=p;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: