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

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;
相关推荐
xnglan16 小时前
数据结构与算法:队列的表示和操作的实现
c语言·数据结构·算法·链表
刚入坑的新人编程19 小时前
暑期算法训练.11
数据结构·c++·算法·leetcode·链表
朝朝又沐沐21 小时前
算法竞赛阶段二-数据结构(38)数据结构动态链表list
数据结构·算法·链表
寻星探路2 天前
LinkedList与链表
数据结构·链表
junjunyi3 天前
【LeetCode 148】算法进阶:排序链表 ( 归并排序、快速排序、计数排序 )
链表·排序·分治·归并
艾莉丝努力练剑3 天前
【数据结构与算法】数据结构初阶:详解排序(三)——归并排序:递归版本和非递归版本
c语言·开发语言·数据结构·学习·算法·链表·排序算法
朝朝又沐沐4 天前
算法竞赛阶段二-数据结构(36)数据结构双向链表模拟实现
开发语言·数据结构·c++·算法·链表
艾莉丝努力练剑4 天前
【数据结构与算法】数据结构初阶:详解排序(二)——交换排序中的快速排序
c语言·开发语言·数据结构·学习·算法·链表·排序算法
艾莉丝努力练剑4 天前
【LeetCode&数据结构】二叉树的应用(二)——二叉树的前序遍历问题、二叉树的中序遍历问题、二叉树的后序遍历问题详解
c语言·开发语言·数据结构·学习·算法·leetcode·链表