#include <iostream.h>
#include <stdlib.h>
typedef struct Node
{
char data;
struct Node *next;
}Node, *LinkList;
void CreateList(LinkList &head) //创建链表
{
Node *s, *p;
char data;
head = (Node *)malloc(sizeof(Node));
head->next = NULL;
p = head;
while(1)
{
cout << "请输入data:(q退出)" << endl;
cin >> data;
if(data == 'q')
{
break;
}
s = (Node *)malloc(sizeof(Node));
s->next = NULL;
s->data = data;
p->next = s;
p = s;
}
}
int DeleList(LinkList &head, int i, char *e) //删除第i个节点,并把节点的值用e返回
{
Node *p, *q;
p = head->next;
int j = 1;
while(p && j < i-1)
{
p = p->next;
j++;
}
if(!p || j > i-1)
{
return -1;
}
q = p->next;
p->next = q->next;
*e = q->data;
free(q);
return 1;
}
void display(Node *head)
{
Node *p;
p = head->next;
while(p != NULL)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
int InsertList(LinkList &head, int i, char e) // 在第i个位置插入值为e的一个新节点
{
LinkList p, s;
int j = 1;
p = head;
while(p && j < i)
{
p = p->next;
j++;
}
if(!p || j > i)
{
cout << "i的位置不存在" << endl;
return -1;
}
s = (LinkList)malloc(sizeof(Node));
s->data = e;
s->next = p->next;
p->next = s;
return 1;
}
int main()
{
LinkList head;
char e;
CreateList(head);
display(head);
DeleList(head, 3, &e);
display(head);
InsertList(head,5,'m');
display(head);
return 1;
}