寒假項目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;}
運行結果: