需要注意
# include<iostream>
# define MAXLEN 20
# define ElementType char
using namespace std;
typedef struct slNode
{
ElementType x;
struct slNode *next;
}node;
//=====================函数声明======================
void InitialList(node *&L);
int ListLength(node *L);
void GetElement(node *L,int i,ElementType &x);
node *ListLocate(node *L);
void ListInsert(node *&L, int i, ElementType x);
void ListDelete(node*&L, int i);
//=====================主函数========================
int main()
{
node *L;
InitialList(L);
ElementType x;
int i = 0;
ListInsert(L, 0,4);
ListDelete(L, 0);
cout << "输入char型的元素,不大于20个,按\"#\"键结束" << endl;
cin >> x;
while (x != '#')
{
i++;
ListInsert(L, i, x);
cin >> x;
}
i = 0;
for (node *s = L->next; s != NULL; s = s->next)
{
i++;
cout <<"第"<<i<<"个元素为:"<<s->x << endl;
}
system("pause");
return 0;
}
//========================函数定义=========================
void InitialList(node *&L)
{
L = new node;
L->next = NULL;
}
int ListLength(node *L)
{
int i = 0;
for (node *p = L->next; p != NULL; p = p->next)
i++;
return i;
}
node *GetElement(node *L, int i)
{
int j = 1;
node *p = L->next;
for (; p != NULL&&i!=j; p = p->next)
{
j++;
}
if (p == NULL)
cout << "取值序号错误" << endl;
return p;
}
node *ListLocate(node *L,ElementType x)
{
node *p = L->next;
while (p->x != x&&p != NULL)
p = p->next;
if (p == NULL)
cout << "没有该元素" << endl;
return p;
}
void ListInsert(node *&L, int i, ElementType x)
{
node *p = L;
int j = 0;
while (j != i-1&&p!=NULL)
{
p = p->next;
j++;
}
if (p == NULL)
cout << "插入序号错误" << endl;
else
{
node *s = new node;
s->x = x;
s->next = p->next;
p->next = s;
}
}
void ListDelete(node*&L, int i)
{
node *u, *p=L;
int j = 0;
while (j != i - 1 && p != NULL)
{
j++;
p = p->next;
}
if (p == NULL||p->next==NULL)//最后一个节点不可删,当p指向最后一个节点时,p->next==NULL
cout << "删除序号错误" << endl;
else
{
u = p->next;
p ->next = u->next;
delete u;
}
}