删除链表中数据为DATA的所有节点(有头节点)

#include <iostream>
using namespace std;
struct Node{
    
int data;
    Node
* next;
    Node(
const int& t=int()):data(t),next(NULL){}
}
;
Node
* del_node(Node* head,int DATA){
    Node
* p=head;
    Node
* q=head->next;
    
while(q!=NULL){
        
if(q->data!=DATA){
            p
=p->next;
            q
=q->next;
        }

        
else{
            Node
* tmp=q;
            p
->next=q->next;
            q
=q->next;
            delete tmp;
            
//break; 
        }

    }

    
return head;
}


int main()
{
    Node
* head=NULL;
    
int tmp;
    cout
<<"请输入来建立链表:";
    
do{//建立一个<有头结点>的链表,空表就do一次
        cin>>tmp;
        Node
* p=new Node(tmp);
        p
->next=head;
        head
=p;
    }
while(cin.get()!='\n');
    cout
<<"建立的链表如下:"<<endl;
    Node
* p=head->next;
    
while(p!=NULL){
        cout
<<p->data<<' ';
        p
=p->next;
    }

    cout
<<endl;
    cout
<<"请输入要删除的节点:";
    
int x;
    cin
>>x;
    head
=del_node(head,x);
    cout
<<"删除后的链表如下:"<<endl;
    p
=head->next;
    
while(p!=NULL){
        cout
<<p->data<<' ';
        p
=p->next;
    }

    cout
<<endl;    
    p
=head;
    
while(p!=NULL){
        p
=head->next;
        delete head;
        head
=p;
    }

    system(
"pause>nul");
    
return 0;
}

posted on 2011-06-07 17:07 Hsssssss 阅读(202) 评论(0)  编辑 收藏 引用 所属分类: C++代码


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


<2024年5月>
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678

导航

统计

常用链接

留言簿

文章分类

文章档案

收藏夹

搜索

最新评论