單鏈表的插入和刪除 C++實現
#pragma once////定義鏈表和節點///////////////////////////////////////////
////節點類
class Node
{
public:
////methods
Node(void);
Node(int data);
~Node(void);/////members Node* next; int data;};
////鏈表類
class MyLinkTable{
public:
//////methods
void RemovdeAt(int position,Node head);
void Add(Node node,Node head);
void AddAfter(int position,Node head,Node node);
bool IsEmpty(Node head);
void PrintNodes(Node head);
/////members
Node head;
};
///////////////////////////////////////////////實現///////////////////include "StdAfx.h"
include "Node.h"
include <iostream>
/////////node methods/////////////
Node::Node(void)
{
Node::data=0;
Node::next=NULL;
}Node::Node(int data)
{
Node::data = data;
Node::next=NULL;
}Node::~Node(void)
{
}//////////////////////end//////////////////
///////////linkTable methods//////////////
////移除某個節點//////////////////
void MyLinkTable::RemovdeAt(int position,Node* head){
if(this->IsEmpty(head) || position < 0){
return;
}////如果要刪除頭結點
if(position == 0)
{
Node* n = head;
head=head->next;
delete n;
MyLinkTable::head = head;
return;
}Node* p = new Node;
p=head;
for(int i=0;i<position-1&&p!=NULL;p=p->next,i++);if(p!=NULL)
{
Node* n = p->next;
p->next = p->next->next;
free(n);
}
}/////在末尾追加節點
void MyLinkTable::Add(Node node,Node head){
if(this->IsEmpty(head))
{
return;
}
Node* p = head;
while(p->next)
{
p=p->next;
}p->next = node;
node->next = NULL;}
/////在制定位置后面添加節點
void MyLinkTable::AddAfter(int position,Node head,Node node){
if(this->IsEmpty(head)){
return;
}
Node* p = head;
for(int i = 0;i < position && p->next != NULL;p=p->next,i ++);node->next = p->next;
p->next = node;}
////判斷鏈表是否非空
bool MyLinkTable::IsEmpty(Node* head){
return head==NULL;
}////打印鏈表
void MyLinkTable::PrintNodes(Node* head){std::cout<<std::endl; while(head){ std::cout<<head->data<<" "; head=head->next; }}
///////////////end/////////////////// </pre>