链表基本操作

向链表中插入节点的函数操作
struct ListNode
{
int data;
ListNode *next;
};
void add_to_tail(ListNode **pHead,int value)
{
ListNode *pNew = new ListNode();
pNew->data = value;
pNew->next = NULL;
if(*pHead == NULL)
{
*pHead = pNew;
}
else
{
ListNode * pNode = *pHead;
while(pNode->next!=NULL)
{
pNode = pNode->next;
}
pNode->next = pNew;
}
}
最后运行结果为:
这里写图片描述
上面的函数写法中,入参是链表的指针的指针,这样做的原因是当我们入参是一个空链表的时候,实际上如果此时新增节点,那么就会改变链表头指针的值的内容,不然就会造成运行完内容还是空指针。

从链表中删除节点的函数:
void remove_node(ListNode **a,int data)
{
if(*a == NULL || a == NULL)
{
return ;
}
ListNode *toBeDeleted ;
if((*a)->data == data)
{
toBeDeleted = *a;
*a = (*a)->next;
}
else
{
ListNode *pHead = *a;
while(pHead->next!=NULL&&pHead->next->data!=data)
pHead= pHead->next;
toBeDeleted = pHead->next;
pHead->next = pHead->next->next;
}
delete toBeDeleted;
toBeDeleted = NULL;
}

逆序输出链表:
这个函数中用到了stack这个栈,这个结构可以后进先出的结构,需要注意的是top()方法是取出栈顶元素,pop()方法弹出元素,但是不会返回弹出的元素,而且需要添加头文件stack.h
void PrintListReversingly_Iteratively(ListNode *pHead)
{

std::stack<ListNode *> nodes;
ListNode * pNode = pHead;
while(pNode!=NULL)
{
    nodes.push(pNode);
    pNode = pNode->next;
}
while(!nodes.empty())
{
    pNode = nodes.top();
    cout<<pNode->data<<"\t";
    nodes.pop();
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

孙仲谋111

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值