关于链表的基本操作

#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;
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值