---
title: "单链表-数据结构"
description: "单链表...看起来简单，写起来难"
canonical_url: "https://yangqiuyi.com/blog/suan-fa/shu-ju-jie-gou/dan-lian-biao-shu-ju-jie-gou"
---

> Index of every page on this site: [llms.txt](https://yangqiuyi.com/llms.txt)

单链表...看起来简单，写起来难

```cpp
#include <bits/stdc++.h>

using namespace std;

typedef struct Node
{
    int data;
    Node *next;
}Lnode,*Pnode;

void nodeInit(Pnode pnode)
{
    pnode->next=NULL;
}

void headinsert(Pnode pnode,int e)
{
    Pnode newnode = (Pnode)malloc(sizeof(Node));
    newnode->data=e;
    newnode->next=pnode->next;
    pnode->next=newnode;
}

void dump(Pnode node)
{
    node=node->next;
    while(node)
    {
        cout<<node->data<<" ";
        node=node->next;
    }
    cout<<endl;
}

Pnode lastNode(Pnode node)
{
    while (node)
    {
        node=node->next;
    }
    return node;
}

void insertNode(Pnode pnode,int pos,int e)
{
    Pnode newnode = (Pnode)malloc(sizeof(Node));
    newnode->data=e;
    while(pnode && pos>1)
    {
        pos--;
        pnode=pnode->next;
    }
    newnode->next=pnode->next;
    pnode->next=newnode;
}

void tailInsert(Pnode pnode,int e)
{
    while(pnode->next)
    {
        pnode=pnode->next;
    }
    Pnode newnode =(Pnode)malloc(sizeof(Node));
    newnode->data=e;
    newnode->next=NULL;
    pnode->next=newnode;
}

int main()
{
    Lnode node;
    nodeInit(&node);
    headinsert(&node,1);
    headinsert(&node,2);
    insertNode(&node,2,3);
    tailInsert(&node,1);
    dump(&node);
    return 0;
}
```

## Sitemap

See the full [sitemap](https://yangqiuyi.com/sitemap.md) for all pages.
