#include<iostream>
using namespace std;
typedef struct node
{
int data;
struct node *next;
}Node, *List;
//建立带头结点的单链表
List createList()
{
Node *head, *p1, *p2;
p1 = p2 = head = new Node;//头结点
int num;
cin >> num;
while(-1 != num)
{
p1 = new Node;
p1->data = num;
p2->next = p1;
p2 = p1;
cin >> num;
}
p2->next = NULL; //不可少
return head;
}
int getListLength(List p)
{
int length = 0;
while(NULL != p->next)
{
length++;
p = p->next;
}
return length; //不包括头结点
}
//把element插入到第position个位置
List insertNode(List p, int position, int element)
{
int length = getListLength(p);
if(position < 1 || position > length + 1)
{
cout << "wrong position" << endl;
exit(1);
}
Node *p1 = p ->next;
Node *p2 = p;
int i;
for(i = 0; i < position - 1; i++)
{
p2 = p1;
p1 = p1->next;
}
Node *s = new Node;
s->data = element;
p2->next = s;
s->next = p1;
return p;
}
List delNode(List p, int num)
{
Node *p1 = NULL, *p2 = NULL;
if(NULL == p->next)
return p;
p1 = p->next;
p2 = p; //不可少
//注意while中条件的顺序
while(NULL != p1 && num != p1->data)
{
p2 = p1;
p1 = p1->next;
}
//注意if中条件的顺序
if(NULL == p1)
cout << "not been found" << endl;
else
{
p2->next = p1->next;
delete p1;
}
return p;
}
void printList(List p)
{
while(NULL != p->next)
{
cout << p->next->data << " ";
p = p->next;
}
cout << endl;
}
//下面采用递归释放(也可循环释放)
void releaseList(List p)
{
if(NULL == p->next)
delete p;
else
{
releaseList(p->next);
delete p;
}
}
int main()
{
List head = createList();
printList(head);
int position = 4;
int element = 100;
head = insertNode(head, position, element);
printList(head);
int num = 3;
head = delNode(head, num);
printList(head);
releaseList(head);
return 0;
}