该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
list.cpp:
#include"list.h"
#include
template
LinkedList::LinkedList(LinkedList &List)
{
ListNode*srcptr = List.first->link;
first = new ListNode;
ListNode*destptr = first;
while (srcptr)
{
destptr->link = new ListNode(srcptr->data);
destptr = destptr->link;
srcptr = srcptr->link;
++len;
}
destptr->data = NULL;
}
template
void LinkedList::MakeEmpty(void)
{
ListNode *p;
while (first->link)
{
p = first->link;
first->link = p->link;
delete p;
}
len = 0;
return;
}
template
ListNode*LinkedList::GetElem(int k)const
{
if (k<1 || k>len)
{
cout<
return NULL;
}
ListNode*p = first->link;
for (int i = 1; p&&i < k;i++)
{
p = p->link;
}
return p;
}
template
ListNode* LinkedList::LocateElem(const T val)const
{
ListNode*p = first->link;
while (p)
{
if (p->data == val)
{
return p;
}
p = p->link;
}
return NULL;
}
template
bool LinkedList::ListInsert(int k,T val)
{
if (k<1 || k>len + 1)
{
cout<
return false;
}
ListNode*p = first, *newPtr;
for (int j = 0; j < k - 1; j++)
{
p = p->link;
}
newPtr = new ListNode(val);
newPtr->link = p->link;
p->link = newPtr;
len++;
return true;
}
template
bool LinkedList::ListDelete(int k, T&val)
{
if (k<1 || k>len)
{
cout << "插入位置错误" <
return false;
}
if (!first->link)
{
cout << "空表不能删除" <
return false;
}
ListNode*p = first;
for (int j = 0; j < k - 1; j++)
{
p = p->link;
}
ListNode*q = p->link;
p->link = q->link;
val = q->data;
delete q;
len--;
return true;
}
template
void LinkedList::CreateList(istream &in)
{
ListNode *p;
T val;
int i = 1, n;
cout << "新建一个链表:" << endl;
cout << "输出结点的个数:";
in >> n;
while (i <= n)
{
cout << "输入第" << i << "个结点的值";
in >> val;
p = new ListNode(val);
p->link = first->link;
first->link = p;
++i;
}
len = i - 1;
}
template
istream& operator>>(istream &in, LinkedList &List)
{
List.CreateList(in);
return in;
}
template
void LinkedList::TraverseList(ostream &out)
{
ListNode*p = first->link;
out << "单链表中结点的值为:" <
while (p)
{
out <data <
p = p->link;
}
out<
}
template
ostream& operator<&List)
{
List.TraverseList(out);
return out;
}