class List;
class ListNode{
friend class List;
int data;
ListNode *next;
public:
ListNode(){next=NULL;}
ListNode(int data,ListNode *next):data(data),next(next){}
};
class List{
ListNode *Head;
public:
List()
{
Head=new ListNode();
Head->next=NULL;
}
void InsertPreNode(const int &data);
void InsertEndNode(const int &data);
void InsertNode(const int &index,const int &data);
void DeleteNode(const int &index);
void PrintList()const;
};
void List::InsertPreNode(const int &data)//插入节点
{
ListNode *p=NULL;
p=new ListNode();
p->data=data;
p->next=NULL;
p->next=Head->next;
Head->next=p;
}
void List::InsertEndNode(const int &data)//插入节点
{
ListNode *p=NULL;
p=new ListNode();
p->data=data;
p->next=NULL;
ListNode *q=NULL;
q=Head;
while(q->next!=NULL)
q=q->next;
q->next=p;
}
void List::InsertNode(const int &index,const int &data)//插入节点
{
assert(index>0);
ListNode *p,*q;
q=Head;
p=Head->next;
for(int i=1;i<index&&p!=NULL;i++)
{
q=p;
p=p->next;
}
ListNode *NewNode=new ListNode();
NewNode->data=data;
NewNode->next=NULL;
NewNode->next=p;
q->next=NewNode;
}
void List::DeleteNode(const int &index)//删除节点
{
ListNode *p,*q;
p=Head->next;
q=Head;
for(int i=1;i<index&&p!=NULL;i++)
{
q=p;
p=p->next;
}
if(p!=NULL)
q->next=p->next;
}
void List::PrintList()const//打印
{
ListNode *p;
p=Head->next;
while(p!=NULL)
{
printf("%d-",p->data);
p=p->next;
}
}
int main(array<System::String ^> ^args)
{
List list;
list.InsertPreNode(4);
list.InsertPreNode(2);
list.InsertPreNode(8);
list.InsertEndNode(5);
list.InsertEndNode(1);
list.InsertNode(2,10);
list.PrintList();
printf("/n");
list.DeleteNode(1);
list.PrintList();
printf("/n");
list.DeleteNode(10);
list.PrintList();
getchar();
return 1;
}