寒假項目1-動態鏈表體驗(改造)(4),寒假1-

來源:互聯網
上載者:User

寒假項目1-動態鏈表體驗(改造)(4),寒假1-

/* * Copyright (c) 2014, 煙台大學電腦學院 * All rights reserved. * 檔案名稱:test.cpp * 作    者:劉暢 * 完成日期:2015 年 1  月  22  日 * 版 本 號:v1.0 * * 問題描述:改造博文樣本中的鏈表。  * 輸入描述:輸入n(n為結點資料)。* 程式輸出:輸出動態鏈表


(4)編寫函數delete_node(int x),刪除結點值為x的結點。

#include <iostream>#include <cstdio>using namespace std;struct Node{    int data;                   //結點的資料    struct Node *next;          //指向下一個結點};Node *head=NULL;                //將鏈表頭定義為全域變數,以便後續操作void make_list2();              //建立鏈表void out_list();                //輸出鏈表void delete_node(int x);        //刪除x結點int main(){    int x;    cin>>x;    make_list2();    out_list();    delete_node(x);    out_list();    return 0;}void make_list2(){    int n;    Node *p,*q;                   //p用於指向建立立的結點, q指向鏈表尾部    cout<<"輸入若干正數(以0或一個負數結束)建立鏈表:"<<endl;    cin>>n;    while(n>0)    {        p=new Node;               //建立一個新結點        p->data=n;                //將n放入新結點的資料成員中        p->next=NULL;             //將指標P指向的next置空        if(head==NULL)            head=p;        else            q->next=p;        q=p;                      //將p鏈入表尾        cin>>n;    }    return;}void out_list(){    Node *p=head;    cout<<"鏈表中的資料為:"<<endl;    while (p!=NULL)    {        cout<<p->data<<" ";        p=p->next;    }    cout<<endl;    return;}void delete_node(int x){    Node *p,*q;    if (head==NULL)        cout<<"空鏈表,無法刪除。"<<endl;    else    {        while (head!=NULL&&head->data==x)        {            p=head;            head=head->next;            delete p;        }        if (head!=NULL)        {            p=head;            q=p->next;            while (q!=NULL)            {                if (q->data==x)                {                    p->next=q->next;                    delete q;                }                else                {                    p=q;                }                q=p->next;            }        }        cout<<"已更新鏈表..."<<endl;    }    return;}

運行結果:


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.