链表的基本操作:创建、插入、删除操作对应c/c++代码

版权声明:转载请注明出处哦~ https://blog.csdn.net/Cassie_zkq/article/details/82154329
  • 链表的创建

#include <iostream>
#include <stdlib.h>
using namespace std;
struct node{
    int data;//数据域
    node *next;//指针域
};
node* create(int array[])
{
    node *head,*p,*pre;
    head=new node;//头结点
    head->next=NULL;
    pre=head;
    for(int i=0;i<5;i++)
    {
        p=new node;//新结点
        p->data=array[i];
        p->next=NULL;
        pre->next=p;
        pre=p;
    }
    return head;
}
int main()
{
    int array[5]={1,2,3,4,5};
    node *l=create(array);
    l=l->next;//第一个结点开始才有数据域
    while(l!=NULL)
    {
        printf("%d ",l->data);
        l=l->next;
    }
    return 0;
}

输出:1 2 3 4 5

  • 插入元素

如在第三个位置插入9(从1开始数,因为【0,pos-1))

#include <iostream>
#include <stdlib.h>
using namespace std;
struct node{
    int data;//数据域
    node *next;//指针域
};
node* create(int array[])
{
    node *head,*p,*pre;
    head=new node;//头结点
    head->next=NULL;
    pre=head;
    for(int i=0;i<5;i++)
    {
        p=new node;//新结点
        p->data=array[i];
        p->next=NULL;
        pre->next=p;
        pre=p;
    }
    return head;
}
void insert(node *head,int pos,int x)
{
    node *p=head;
    for(int i=0;i<pos-1;i++)
        p=p->next;//找到插入位置的前一个结点
    node *q=new node;//新建结点
    q->data=x;
    q->next=p->next;
    p->next=q;
}
int main()
{
    int array[5]={1,2,3,4,5};
    node *l=create(array);
    insert(l,3,9);
    l=l->next;//第一个结点开始才有数据域
    while(l!=NULL)
    {
        printf("%d ",l->data);
        l=l->next;
    }
    return 0;
}

输出:1 2 9 3 4 5

  • 删除元素

删除链表上所有值为x的结点

#include <iostream>
#include <stdlib.h>
using namespace std;
struct node{
    int data;//数据域
    node *next;//指针域
};
node* create(int array[])
{
    node *head,*p,*pre;
    head=new node;//头结点
    head->next=NULL;
    pre=head;
    for(int i=0;i<5;i++)
    {
        p=new node;//新结点
        p->data=array[i];
        p->next=NULL;
        pre->next=p;
        pre=p;
    }
    return head;
}
void del(node *head,int x)
{
    node *p=head->next;//从第一个结点开始
    node *pre=head;//pre为p的前驱结点
    while(p!=NULL)
    {
        if(p->data==x)
        {
            pre->next=p->next;
            delete(p);
            p=pre->next;
        }
        else
        {
            pre=p;
            p=p->next;
        }
    }
}
int main()
{
    int array[5]={1,2,3,4,5};
    node *l=create(array);
    del(l,3);
    l=l->next;//第一个结点开始才有数据域
    while(l!=NULL)
    {
        printf("%d ",l->data);
        l=l->next;
    }
    return 0;
}

输出:1 2 4 5

猜你喜欢

转载自blog.csdn.net/Cassie_zkq/article/details/82154329