#include<iostream>
using namespace std;
typedef struct list
{
int data;
struct list* next;
}List;
一、链表的创建
List* create()
{
List* head = new List();
List* out = head;
int cycle = 1;
int x; //用于初始化链表节点的数据
while (cycle)
{
cin >> x;
if (x != 0)
{
List* tmp = new List();
tmp->data = x;
head->next = tmp;
head = head->next;
}
else
cycle = 0;
}
head->next=NULL;
out = out->next;
return out;
}
二、链表的插入
List* head=create();//已创建的链表
List* i=head;
List* funcAdd(int n,int data)//第n个节点插入data数据
{
int cnt=0;
List* temp=new List();
temp->data=data;
for(;i!=NULL;i=i->next)
{
if(cnt==n&&cnt==0) //头部插入
{
temp->next=head;
break;
}
if(cnt==n&&cnt>0&&i->next!=NULL) //中部插入
{
temp->next=i->next;
i->next=temp;
break;
}
if(cnt==n&&i->next!=NULL) //尾部插入
i->next=temp;
++cnt;
}
return head;
}
三、链表的删除
List* head=create();//已创建的链表
List* pre=head;
List* cur=pre->next;
int cnt=0;
List* funcDelete(int index) //表示删除链表第几个节点
{
if(index=0)
{
i=i->next;
return;
}
while(cur!=NULL)
{
if(cnt==index)
{
pre->next=cur->next;
break;
}
pre=cur;
cur=cur->next;
++cnt;
}
return head;
}
四、返回链表长度
List* head=create();//已创建的链表
int cnt=0;
int funcLength()
{
fot(List* i=head;i!=NULL;i=i->next)
++cnt;
return cnt;
}
五、链表的倒序
List* head=create();//已创建的链表
List* funcReverse()
{
List* node=head;
List* pre=NULL;
List* NEXT;
while(node!=NULL)
{
NEXT=node->next;
node->next=pre;
pre=node;
node=NEXT;
}
return node;
}
六、链表的排序
List* head=create();//已创建的链表
List* node1=head;
List* node2;
//**采用选择排序
List* funcSort()
{
while(node1!=NULL)
{
node2=node1->next;
while(node2!=NULL)
{
if(node1->data>node2->data)
{
int temp=node2->data;
node2->data=node1->data;
node1->data=temp;
}
node2=node2->next;
}
node1=node1->next;
}
}