给你一个百分百正确的程序,带正确的运行结果,如有任何问题,欢迎随时跟我交流:-)
代码如下:
#include
#include
using namespace std;
struct node
{ int data;
struct node * next;
};
typedef struct node NODE;
typedef struct node * PNODE;
void AddNode(PNODE h, int num)
{
PNODE p = h, n;
n = new NODE;
n->data = num;
while (p->next != NULL)
p = p->next;
p->next = n;
n->next = NULL;
}
void PrintList(PNODE head)
{ PNODE p;
p = head->next;
while (p != NULL)
{
cout << p->data << endl;
p = p->next;
}
}
int GetLength(PNODE head)
{
PNODE p = head->next;
int len = 0;
while (p != NULL)
{
p = p->next;
len++;
}
return len;
}
void InsertNode(PNODE h, int k, int data)
{
int i = 0;
PNODE p = h;
if ( (k > GetLength(h) + 1) || (k < 1))
{
cerr << "Invalid position k: " << k << endl;
exit(-1);
}
while (++i < k)
{
p = p->next;
}
PNODE n = new NODE;
n->data = data;
n->next = p->next;
p->next = n;
}
void DeleteNode(PNODE h, int k)
{
int i = 0;
PNODE p = h;
int len = GetLength(h);
if ( (k >= len) || (k <= 0))
{
cerr << "Invalid position k: " << k << endl;
exit(-1);
}
while (++i < k)
{
p = p->next;
}
PNODE q = p->next;
p->next = q->next;
q->next = NULL;
delete q;
}
int main(void)
{
int num = 1;
int k = 0;
PNODE head;
head = new NODE;
head->next = NULL;
head->data = -1;
for (int i = 1; i < 10; i++)
{
AddNode(head, i);
}
cout << "新建完成后,打印链表的结果如下:" << endl;
PrintList(head);
cout << "当前链表长度为: " << GetLength(head) << endl;
cout << "请输入插入点k: ";
cin >> k;
cout << "请输入要插入的数据data: ";
int data = 0;
cin >> data;
InsertNode(head, k, data);
cout << "插入后,打印链表的结果如下:" << endl;
PrintList(head);
cout << "当前链表长度为: " << GetLength(head) << endl;
cout << "请输入要删除的结点的序号k: ";
cin >> k;
DeleteNode(head, k);
cout << "删除后,打印链表的结果如下:" << endl;
PrintList(head);
cout << "当前链表长度为: " << GetLength(head) << endl;
return 0;
}
运行结果为:
新建完成后,打印链表的结果如下:
1
2
3
4
5
6
7
8
9
当前链表长度为: 9
请输入插入点k: 2
请输入要插入的数据data: 18
插入后,打印链表的结果如下:
1
18
2
3
4
5
6
7
8
9
当前链表长度为: 10
请输入要删除的结点的序号k: 2
删除后,打印链表的结果如下:
1
2
3
4
5
6
7
8
9
当前链表长度为: 9
#include
#include
#include
using namespace std;
typedef struct _node
{
int n;
struct _node *next;
}*node;
node head = NULL;
void addnode(int n)
{
node t;
t = (node)malloc(sizeof(*t));
t->n=n;
t->next=head;
head = t;
}
int count()
{
int n = 0;
node t;
for (t = head; t; t=t->next)
n++;
return n;
}
void insert(int k)
{
int n = 1;
node t,x;
for (t = head; t; t=t->next,++n)
{
if (n == k)
{
x = (node)malloc(sizeof(*t));
x->n = k;
t->next=x;
x->next = t->next;
return ;
}
}
}
void del(int k)
{
int n = 1;
node x,y;
for (y=x=head; x; y = x, x=x->next,++n)
{
if (n == k)
{
/*删除头节点*/
if (x == y)
{
head=head->next;
x->next = NULL;
free(x);
return ;
}
else
{
y->next = x->next;
x->next = NULL;
free(x);
return ;
}
}
}
}
int main(void)
{
int i = 0;
int k;
/*生成10个节点的链表*/
for (i = 0; i < 10; ++i)
{
addnode(i);
}
printf("节点个数%d\n", count());
printf("插入位置k的值:");
scanf(" %d", &k);
insert(k);
del(k);
return 0;
}
不知道include
#include
#include
using namespace std