**
链表的常规操作(删除对应值的所有链表节点,对链表节点升序,对链表节点翻转)
**
#define _CRT_SECURE_NO_WARNINGS
#include<string>
#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
int id;
struct Node *next;
}Node;
Node *SListCreat()
{
Node *head = NULL;
head = (Node*)malloc(sizeof(Node));
head->id = -1;
head->next = NULL;
Node *pcur = head;
Node *pnew = NULL;
while (1)
{
int id ;
printf("请输入节点id:");
scanf("%d", &id);
if (id==-1)
{
break;
}
pnew = (Node*)malloc(sizeof(Node));
pnew->id = id;
pnew->next = NULL;
pcur->next = pnew;
pcur = pcur->next;
}
return head;
}
int SListprint(Node *head)
{
if (head==NULL)
{
return -1;
}
while(head != NULL)
{
printf("%d->",head->id);
head = head->next;
}
printf("NULL\n");
return 0;
}
int SListdelect(Node *head,int a)
{
if (head==NULL)
{
return -1;
}
Node *tem = head;
Node *pcur = tem->next;
int flag = 0;//设置一个标志位,1是当遇到要删除id时的处理,0是没有遇到要删除id的处理。
while (pcur != NULL)
{
if (pcur->id==a)
{
tem->next = pcur->next;
free(pcur);
pcur = NULL;
flag = 1;
}
if (flag==0)
{
tem = pcur;
pcur = pcur->next;
}
else
{
pcur = tem->next;
flag = 0;
}
}
//如果在最末尾,就得2换办法
return 0;
}
int SListrang(Node *head)
{
Node *pcur = NULL;
Node *pnew = NULL;
Node tem;
for( pcur=head->next; pcur->next !=NULL; pcur=pcur->next)//pcur取不到最后一个节点
{
for (pnew=pcur->next; pnew !=NULL; pnew=pnew->next)//pnew是后面一个节点
{
if (pcur->id > pnew->id)//升序操作
{
tem = *pnew;
*pnew = *pcur;
*pcur = tem;
tem.next = pnew->next;
pnew->next = pcur->next;
pcur->next = tem.next;
}
}
}
return 0;
}
int SListnodereverse(Node *head)
{
Node *pre = head->next;
Node *pcur = pre->next;
pre->next = NULL;
while (pcur !=NULL)
{
Node *tem;
tem = pcur->next;
pcur->next = pre;
pre = pcur;
pcur = tem;
}
head->next = pre;
return 0;
}
int main()
{
Node *head = NULL;
head=SListCreat();//创建一个输入id的新节点
printf("创建的新节点:");
SListprint(head);
SListdelect(head, 3);//删除链表节点中id为3的的所有节点
printf("删除所有id为3的节点后:");
SListprint(head);
SListrang(head);//对链表节点的id进行升序
printf("对链表节点的id进行升序后:");
SListprint(head);
SListnodereverse(head);
printf("对链表节点进行翻转之后:");
SListprint(head);
system("pause");
}