1. 程式人生 > >資料結構課後練習

資料結構課後練習

就保平佈置的那個必做題。。。

題目:在一個按值遞增的連結串列中刪除值等於x的節點,成功返回1,失敗返回0.

原始碼如下:

#include<iostream>
#include<stdlib.h>
using namespace std;
class node {
	node* next;
	int data;
public:
	node() {}
	~node() {}
	node* create();
	int del(node* head);
};

node* node::create()
{
	node *p, *pa, *head;
	head = new node;
	head->next = NULL;
	pa = head;
	int n;
	cout << "輸入總個數:";
	cin >> n;
	for (int i = 0; i < n; i++)
	{
		p = new node;
		int a;
		cin >> a;
		p->data = a;
		p->next = NULL;
		pa->next = p;
		pa = p;
	}
	return head;
}

int node::del(node* head)
{
	int n;
	cout << "查詢是否存在該數,並刪除:";
	cin >> n;
	int x=0;
	node* p = head->next;
	node* pa = head;
	while (p != NULL)
	{
		if (p->data == n)
		{
			x = 1;
			pa->next = p->next;
			delete(p);
			p = pa->next;
		}
		else
		{
			pa = p;
			p = p->next;
		}
	}
	return x;
}

int main(void)
{
	node A;
	node* L = A.create();
	cout<<A.del(L)<<endl;
	system("pause");
	return 0;
}