//链表线性存储
#include<iostream>
using namespace std;
class Date
{
public:
int date;
Date*next;
};
void show(Date*head); //显示函数
Date*creat(); //链表创建
int Length(Date*head); //长度函数
Date*FindKth(Date*head, int k); //找第k个节点的数
Date*find(Date*head, int m); //返回值为m的对象地址
Date*insert(Date*head, int m, int k); //将m插入到第k个结点
Date*Delete(Date*head, int k); //删除第k个结点
int main()
{
Date*head = NULL, *p = NULL;
head = creat();
show(head);
int l = Length(head);
cout << "长度:" << l << endl;
p = FindKth(head, 2);
cout << '\n' << p->date << endl;
head = insert(head, 34, 3);
show(head);
head = Delete(head, 3);
show(head);
return 0;
}
int Length(Date*head)
{
int i = 0;
while (head)
{
i++;
head = head->next;
}
return i;
}
Date*creat()
{
cout << "创建链表,以-1结束:" << endl;
Date*p = new Date;
cin >> p->date;
Date*p1 = p, *head = p;
while (1)
{
p1 = p;
p = new Date;
cin >> p->date;
if (p->date == -1) //遇到-1退出
{
delete p;
break;
}
p1->next = p;
}
p1->next = NULL;
return head;
}
void show(Date*head)
{
Date *p = head;
cout << "链表数据为:";
while (p)
{
cout << p->date << " ";
p = p->next;
}
cout << endl;
}
Date*FindKth(Date*head, int k)
{
int i = 1;
Date*p = head;
while (p&&i < k)
{
p = p->next;
i++;
}
if (k == i)
return p;
else
return NULL;
}
Date*find(Date*head, int m)
{
Date*p = head;
while (p&&p->date != m)
p = p->next;
return p;
}
Date*insert(Date*head, int x, int k)
{
Date*p = new Date;
Date*p1 = head, *l;
p->date = x;
int i;
if (k == 1) //插在头结点位置
{
p->next = head;
head = p;
}
else if (k > Length(head) + 1)
cout << "插入位置错误:" << endl;
else if (k == Length(head) + 1) //插在末尾位置
{
for (i = 1; i <k - 1; i++)
{
p1 = p1->next;
}
p1->next = p;
p->next = NULL;
}
else
{
for (i = 1; i <k; i++) //插在中间位置
{
l = p1;
p1 = p1->next;
}
l->next = p;
p->next = p1;
}
return head;
}
Date*Delete(Date*head, int k)
{
Date*p = head, *p1;
if (k == 1)
{
head = head->next; //删除头结点
delete p;
}
else if (k > Length(head))
cout << "删除不合法" << endl;
else
{
for (int i = 1; i < k; i++)
{
p1 = p; //删除中间结点
p = p->next;
}
p1->next = p->next;
delete p;
}
return head;
}