链表的操作

#include 

using namespace std;
int aleng = 10;

struct  node
{
    int data=0;
    int nlength=0;
    node *pnext=nullptr;
};

node* creat_link(int length)//创建一个带头节点的链表
{
    node *head,*p, *q;
    p = new node;//p现在开辟了内存
    p->data = -1;//-1表示头节点
    p->nlength = -1;
    head = p;//头节点有了定义
    for (int i = 0; i < length; i++)
    {
        q=new node;//q现在开辟了内存
        q->data = i;
        p->pnext = q;//传递的都是地址
        p = p->pnext;
    }
    return head;
}

node* insert_link(node *pnode,int length,int dat)
{
    node* head = pnode;
    node* q = new node;

    if (length<0||length>aleng)
    {
        return nullptr;
    }
    for (int i = 0; i < length; i++)
    {
        pnode = pnode->pnext;
    }
    q->data = dat;
    q->pnext = pnode->pnext;
    pnode->pnext = q;
    aleng++;
    return head;
}

int main()
{
    node *node1,*head;
    head=node1=creat_link(10);
    for (int i = 0; i < aleng; i++)
    {
        cout << node1->data << "->";
        node1 = node1->pnext;
    }
    cout << endl;

    node1=head;//设置节点开始的位置

    insert_link(node1, 4, 5);
    for (int i = 0; i < aleng; i++)
    {
        cout << node1->data << "->";
        node1 = node1->pnext;
    }
    system("pause");
    return 0;
}

你可能感兴趣的:(链表的操作)