有头结点的链表操作

#include<iostream>
#include <stack>
using namespace std;
struct Node
{
    int data;
    Node *next;
};
//没有头结点的插入新节点
Node* AddNode(Node *head,int num)//如果是void 类型的 那么head要用指向指针的指针
{
    Node *pNew=(Node*)malloc(sizeof(Node));
    pNew->data=num;
    pNew->next=NULL;
    if (head==NULL)
    {
        head=pNew;
    }
    else
    {
        Node *pCur=head;
        while(pCur->next!=NULL)
        {
            pCur=pCur->next;
        }
        pCur->next=pNew;
    }
    return head;
}
//链表无头结点 要删除某个值为val的节点
Node* DeleNode(Node *head,int val)
{
    if (head==NULL)
    {
        return NULL;
    }
    Node *ptobeDelete=NULL;
    if (head->data==val)//如果删除的是头结点
    {
        ptobeDelete=head;
        head=head->next;
    }
    else
    {
        Node *pcur=head;
        while(pcur->next!=NULL&&val!=pcur->next->data)//注意条件判断
        {
            pcur=pcur->next;
        }
        if (pcur->next!=NULL&&pcur->next->data==val)//找到了的话 注意判断条件
        {
            ptobeDelete=pcur->next;
            pcur->next=pcur->next->next;
        }
    }
    if (ptobeDelete!=NULL)//有可能找不到 所以要判断是否为空
    {
        delete ptobeDelete;
        ptobeDelete=NULL;
    }
    return head;
}

//逆序打印不含头结点的链表  头文件为stack
void ReversPrintList(Node *head)
{
    Node *pcur=head;
    stack<Node*>nodes;
    while (pcur!=NULL)//这条语句包含了判断首节点是否为空
    {
        nodes.push(pcur);
        pcur=pcur->next;
    }
    while(!nodes.empty())
    {
        pcur=nodes.top();//访问栈顶元素
        cout<<pcur->data<<endl;
        nodes.pop();
    }
}

//递归方式逆序打印
void ReversPrintListByRecurs(Node *head)
{
    if (head!=NULL)
    {
        if (head->next!=NULL)
        {
            ReversPrintListByRecurs(head->next);//先打印后面的节点
        }
        cout<<head->data<<endl;//再打印前面的节点
    }
}
原文地址:https://www.cnblogs.com/mu-tou-man/p/3951914.html