/* ***********************************************
Author :wsw
Created Time :2016/12/1 15:53:11
TASK :单链表.cpp
LANG :C++
************************************************ */
using namespace std;
typedef int EleType;
typedef struct Node
{
EleType data;//单链表的数据域
struct Node next;//单链表的指针域
}Node,LinkedList;
/////////////////////////////////////
//单链表初始化
LinkedList LinkedListInit(){
Node L;
L = (Node )malloc(sizeof(Node));
if(L == NULL)
printf("申请内存失败");
L -> next = NULL;
}
////////////////////////////////////////
//单链表的建立,头插法建立单链表
LinkedList LinkedListCreateH()
{
int t;
printf("要输入多少个数据:");
scanf("%d",&t);
Node L;
L = (Node )malloc(sizeof(Node));
L -> next = NULL;
EleType x;
while(t--){
scanf("%d",&x);
Node p;
p = (Node )malloc(sizeof(Node));
p ->data = x;
p -> next = L ->next;
L -> next = p;
}
return L;
}
////////////////////////////////////////
//单链表的建立2,尾插法建立单链表
LinkedList LinkedListCreatT()
{
int t;
printf("要输入多少个数据:");
scanf("%d",&t);
Node L;
L = (Node)malloc(sizeof(Node));
L ->next = NULL;
Node r;
r = L;//r始终指向中断节点,开始时指向头节点
EleType x;
while(t--){
scanf("%d",&x);
Node p;
p = (Node )malloc(sizeof(Node));
p ->data = x;
r ->next = p;
r = p;
}
// cout << L->data << endl;
r ->next = NULL;
return L;
}
/////////////////////////////////////////
//单链表的插入,在链表的第i个位置插入x的元素
LinkedList LinkedListInsert(LinkedList L,int i ,EleType x)
{
Node pre;
pre = L;
int tempi = 0;
for(int tempi = 1;tempi < i;tempi++)
{
pre = pre ->next;
}
Node p;
p = (Node )malloc(sizeof(Node));
p ->data = x;
p -> next = pre ->next;
pre ->next = p;
return L;
}
//////////////////////////////////////////
//单链表的删除,在链表中删除值为x的元素
LinkedList LinkedListDelete(LinkedList L,EleType x)
{
Node p,pre;
p = L ->next;
while(p->data!=x)
{
pre = p;
p = p->next;
}
pre ->next = p->next;//删除操作,将其前驱next指向其后继。
free(p);
return L;
}
int main()
{
LinkedList list,start;
list = LinkedListCreatT();
for(start = list -> next;start !=NULL;start = start->next)
{
printf("%d",start->data);
}
printf("\n");
int i;
EleType x;
cout << "输入要插入元素的位置 和数值:" << endl;
scanf("%d %d",&i,&x);
LinkedListInsert(list,i,x);
for(start = list -> next;start !=NULL;start = start->next)
{
printf("%d",start->data);
}
printf("\n");
cout << "输入要删除元素值:" << endl;
scanf("%d",&x);
LinkedListDelete(list,x);
for(start = list -> next;start !=NULL;start = start->next)
{
printf("%d",start->data);
}
printf("\n");
return 0;
}