向链表中插入节点的函数操作
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();
}
}