链表 基本操作

来源:互联网 发布:狄利克雷收敛定理 知乎 编辑:程序博客网 时间:2024/06/10 02:34

 

头插法建立单链表

#include <iostream>
using namespace std;
typedef   char  datatype;
typedef   struct node
{
 datatype  data;
// struct
 node  *next;
}  listnode;
typedef  listnode *   linklist;     //  linklist 是 listnode * 类型
listnode  *p;
 
listnode * createlist( )
{
      char ch;
      linklist head;     // 相当于listnode *head;
      listnode  *p;
      head=NULL;     /*初始化为空*/

      ch=getchar( );
      while (ch!='\n')
       {
            p=new listnode;
           p->data=ch;                  /*数据域赋值*/

           p->next=head;             / *指定后继指针*/
           head=p;                           /*head 指针指定到新插入的结点上*/
           ch=getchar( );
       }
      return (head);
}


int main()
{
   linklist newlist=createlist();
 do
 {
    cout<<newlist->data;
    newlist=newlist->next;
 }while(newlist!=NULL);
 cout<<endl;
 return 0;
}

 

-----------------------------------------------------

 

 

尾插法建立单链表  按序号查找单链表  按值查找单链表  将元素插入到某序号,删除某序号的元素


#include<iostream>
using namespace std;
typedef char datatype;
typedef struct node
{
 datatype data;
 node*next;
}listnode;
typedef listnode* linklist; 

linklist head=NULL;  // 头指针
 linklist r=NULL;      //  指向当前的指针

linklist creat (int n)
 {
    datatype ch; linklist p;    
    for(int i=0;i<n;i++)
    {
     cin>>ch;
     p=new listnode;
     p->data=ch;
     if(head==NULL)
          head=p;         //第一次插入值时 ,把值给头指针
     else
          r->next=p;       //  值插入到当前指针的next 位置
     r=p;                       // 指向当前指针        
    }
    r->next=NULL;  // 结束时,处理
                  return head;
 }

linklist getnode(int a)       //这里a的序号 开始号为 0
{
 for(int i=0;i<a;i++)
 {
    head=head->next;
 }
 return head;
}

linklist locatenode(char b)
{
 linklist phead=head;
 while(phead->next&&phead->data!=b)
 {
  phead=phead->next;
 }
 return phead;
}

linklist insertnode(int j,char c)                     // 将c 插入链表的第j个位置
{
 linklist phead=head; linklist p;
 for(int i=0;i<j-1;i++)                  //  找到插入位置的前一个位置
 {
  phead=phead->next;    
 }
 p=new listnode;
 p->data=c;
 p->next=phead->next;
 phead->next=p;
 return phead;
}


void deletelis(int j)    //  删除 j 位置上的元素
{
 linklist phead=head; linklist q;int i=0;     // q指向要删除位置的前一个位置  ,phead指向 要删除位置的序号
 while(phead&&i<j)
 {
  q=phead;     
  phead=phead->next;
  i++;
 }
 q->next=phead->next;
 delete(phead);
}

linklist input()                                    // 输出链表中的内容
 {
 linklist phead=head;
 while(phead!=NULL)
 {
  cout<<phead->data<<" ";
  phead=phead->next;
 }
 return phead;
}

int main()
{
 int n;cin>>n;
 linklist newlist=creat(n);

 while(newlist!=NULL)
 {
  cout<<newlist->data;
  newlist=newlist->next;
 }
                int a;cin>>a;
 cout<<getnode(a)->data<<endl;
                char b; cin>>b;
 cout<<locatenode<<" "<<locatenode(b)->data<<endl;
                deletelis(4);
 return 0;
}
------------------------------------------------------------------------------

 

原创粉丝点击