双向链表,对其实现头插入,尾插入以及遍历倒序输出

1.创建一个节点,并将链表的首节点返回

创建一个独立节点,没有和原链表产生任何关系

cs 复制代码
#include "head.h"

typedef struct Node
{
int num;
struct Node*pNext;
struct Node*pPer;
}NODE;

后续代码:

cs 复制代码
NODE*createNode(int value)
{
    NODE*new node=(NODE*)malloc(sizeof(NODE));
    if(NULL==new node)
    {
        perror("createNode malloc fail");
        return NULL;
    }
    new node->num=value;
    new node->pNext=NULL;
    new node->pPer=NULL;
    return new node;
}

//头插法

cs 复制代码
NODE*instetHead(NODE*head,int value)
{
    NODE*new node=createNode(value);
    if(NULL==new code)
    {
        //新节点创建失败
        return head;
    }

    if(head==NULL)
    {
    //原链表为空
    return new node;
    }
    new node->pNext=head;
    head->pPer=new node;
    return new node;
}

//获取链表的尾节点指针

cs 复制代码
NODE*getListTail(NODE*head)
{
    if(head==NULL)
    {
        return NULL;
    }

    while(head->pNext!=NULL)
    {
        head=head->pNext;
    }
     return head;
}

NODE*currentPosNOde(NODE*head,int pos)
{
    if(head==NULL)
    {
        return NULL;
    }
    for(int i=0;i<pos-1;i++)
    {
        head=head->pNext;
    }
    return head;
}

//pos=0时为头插法

//当前函数不处理头插和尾插的情况

cs 复制代码
NODE*insertMid(NODE*head,int value,int pos)
{
    NODE*new node=createNode(value);
    if(NULL==new node)
    {
    //新节点创建失败
    return head;
    }
    if(head==NULL)
    {
        //原链表为空
        return new node;
    }

//获取pos位置的节点指针

cs 复制代码
NODE*cur=currentPosNode(head,pos);

//将新节点与其插入位置之后的节点进行连接

cs 复制代码
new node->pNext=cur->pNext;
cur->pNext->pPer=cur;

    return head;
相关推荐
近津薪荼2 小时前
递归专题(2)——合并链表
c++·学习·算法·链表
小龙报3 小时前
【数据结构与算法】单链表核心精讲:从概念到实战,吃透指针与动态内存操作
c语言·开发语言·数据结构·c++·人工智能·算法·链表
青桔柠薯片18 小时前
数据结构:单向链表,顺序栈和链式栈
数据结构·链表
-dzk-21 小时前
【代码随想录】LC 203.移除链表元素
c语言·数据结构·c++·算法·链表
_F_y1 天前
链表:重排链表、合并 K 个升序链表、K 个一组翻转链表
数据结构·链表
senijusene1 天前
数据结构:单向链表(2)以及双向链表
数据结构·链表
senijusene1 天前
数据结构与算法:栈的基本概念,顺序栈与链式栈的详细实现
c语言·开发语言·算法·链表
执着2592 天前
力扣hot100 - 234、回文链表
算法·leetcode·链表
踩坑记录2 天前
leetcode hot100 23. 合并 K 个升序链表 hard 分治 迭代
leetcode·链表
会飞的战斗鸡2 天前
JS中的链表(含leetcode例题)
javascript·leetcode·链表