链表的实现(C++语言)


<span style="font-size:18px;">// LinkedList2.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <fstream>

typedef int ElemType;

using namespace std;



struct Node
{
	ElemType elem;
	Node* pNext;

} Node;

typedef struct Node* PNode;

class LinkedList
{
private:
	PNode  pHead;

public:
	LinkedList(int i)
	{	
		PNode  pNew,pTail;
		pHead=(PNode)new PNode;
		pTail=pHead;
		for(int j=0;j<i;j++)
		{
			pNew=(PNode)new PNode;
			pTail->pNext=pNew;
			pNew->elem=j+1;
			pNew->pNext=NULL;
			pTail=pNew;
			cout << "pTail=" << pTail << "  pHead=" << pHead << endl;
		}
	}
	
	~LinkedList()
	{
		PNode p=pHead;
		PNode q;
		ofstream out_file("text.txt" );
			if ( ! out_file )
			   { cerr << "oops! unable to open output file\n";  }
		while(p->pNext)
		{
			//cout << p->elem << ' ';
			q=p;
			p=p->pNext;
			cout << "free:" << q << endl;
			delete q;
			q=NULL;
			//free(q);
			out_file << "free:" << q << endl;
		}
		delete p;
		p=NULL;
	}

	void Show()
	{
		PNode p=pHead->pNext;
		while(p!=NULL)
		{
			cout << p->elem << ' ';
			p=p->pNext;
		}
		cout << endl;
	}

	PNode GetElem(int i)
	{
		PNode pn=pHead;
		int j=0;
		while(pn->pNext && j<i)
		{
			cout << "pn=" << pn << ' ';
			pn=pn->pNext;
			j++;
		}
		cout << "return-pn=" << pn << endl;
		return pn;
	}

	bool Insert(ElemType elem, int i)
	{
		PNode p=(PNode)new PNode();
		PNode q;
		p->elem=elem;
		q=GetElem(i-1);
		p->pNext=q->pNext;
		q->pNext=p;

		return true;
	}

	ElemType Delete(int i)
	{
		PNode p=GetElem(i);
		GetElem(i-1)->pNext=p->pNext;
		return p->elem;
	}
	
};

int main(void)
{
	
	LinkedList* _ll=new LinkedList(5);
	_ll->Show();
	//delete _ll;
	_ll->Insert(111,4);
	_ll->Insert(222,4);
	//_ll->GetElem(3);
	_ll->Show();
	cout << "您删除的元素是:" << _ll->Delete(5) << endl;
	_ll->Show();

	system("pause");
	return 0;
}</span>


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值