カテゴリー
C++

望洋先生のC++入門、線形リスト

lists.h

#pragma once

#include <stdio.h>
#include <string.h>

class Link {
	friend class List;
	Link* next;
	char item[20];

public:
	Link(const char* x = "") { 
		strcpy_s(item, x);
		next = NULL;
	}
	Link* Next(void) { return (next); }
	void LinkPrint(void) { printf("%s\n", item); }
};

class List {
protected:
	Link* first;
	Link* last;
public:
	List(void) { first = last = new Link; }
	~List() { Clear(); delete first; }
	List& Insert(const Link&);
	List& Append(const Link&);
	List& Delete(void);
	List& Remove(void);
	List& Clear(void);
	void Print(void);
};

list.cpp

#include <stdio.h>
#include "list.h"

//-----先頭に要素を追加-----
List& List::Insert(const Link& x)
{
	Link* ptr = first;
	first = new Link;
	*first = x;
	first->next = ptr;
	return (*this);
}

//-----末尾に要素を追加-----
List& List::Append(const Link& x)
{
	Link* ptr = last;
	*ptr = x;
	last = new Link;
	ptr->next = last;
	return (*this);
}

//----先頭要素を削除-----
List& List::Delete(void)
{
	if (first != last) {
		Link* ptr = first->next;
		delete first;
		first = ptr;
	}
	return (*this);
}

//-----末尾要素を削除-----
List& List::Remove(void)
{
	if (first != last) {
		Link* now = first;
		Link* pre = last;
		while (now->next != last) {
			pre = now;
			now = now->next;
		}
		pre->next = last;
		delete now;
	}
	return (*this);
}

//-----全要素を削除-----
List& List::Clear(void)
{
	Link* ptr = first;
	while (ptr != last) {
		Link* next = ptr->next;
		delete ptr;
		ptr = next;
	}
	first = last;
	return (*this);
}

//-----全要素を表示-----
void List::Print(void)
{
	puts("===== リ ス ト 一 覧=====");
	int no = 1;
	Link* ptr = first;
	while (ptr != last) {
		printf("%d : ", no++);
		ptr->LinkPrint();
		//putchar('\n');
		ptr = ptr->next;
	}
}

実行部分

#include "list.h"

int main()
// ConsoleApplication1.cpp : このファイルには 'main' 関数が含まれています。プログラム実行の開始と終了がそこで行われます。
//
{
	List L7;

	L7.Append(Link("柴田"));
	L7.Insert(Link("大賀"));
	L7.Append(Link("具島"));
	L7.Append(Link("増田"));
	L7.Append(Link("鈴木"));
	L7.Print();
	L7.Remove();
	L7.Print();
	L7.Insert(Link("伊藤"));
	L7.Print();
	L7.Delete();
	L7.Print();
	L7.Clear();
	L7.Print();
	return (0);
}

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

inserted by FC2 system