《剑指Offer》面试题5:从尾到头打印链表
面试常考:链表末尾添加一个新结点&找到结点并删除
#include <iostream>
using namespace std;
struct ListNode
{
int value;
ListNode *next;
};
//往该链表的末尾添加一个结点
void AddToTail(ListNode **pHead, int value)
{
ListNode *pNew = new ListNode();
pNew->value = value;
pNew->next = NULL;
if (*pHead = NULL)
*pHead = pNew;
else
{
ListNode *pNode = *pHead;
while (pNode->next != NULL)
{
pNode = pNode->next;
}
pNode->next = pNew;
}
}
//在链表中找到第一个含有某值的结点并删除该结点
void RemoveNode(ListNode** pHead, int value)
{
if (pHead == NULL || *pHead == NULL)
return;
ListNode* pToBeDeleted = NULL;
if ((*pHead)->value == value)
{
pToBeDeleted = *pHead;
*pHead = (*pHead)->next;
}
else
{
ListNode *pNode = *pHead;
while (pNode->next != NULL && pNode->value != value)
{
pNode = pNode->next;
}
if (pNode->next != NULL && pNode->value == value)
{
pToBeDeleted = pNode;
pNode = pNode->next;
}
if (pToBeDeleted != NULL)
{
delete pToBeDeleted;
pToBeDeleted = NULL;
}
}
}
知识点
1.单向链表
2.循环、递归和栈3个相互关联的概念理解
题目描述
输入一个链表的头结点,从尾到头反过来打印出每个结点的值。
链表结点定义如下。
struct ListNode
{
int value;
ListNode *next;
};
解题思路及代码(原书)
#include <stack>
using namespace std;
struct ListNode
{
int value;
ListNode *next;
};
// 用栈实现
void PrintListReversingly_Iteratively(ListNode* pHead)
{
stack<ListNode*> nodes;
ListNode* pNode = pHead;
while (pNode != NULL)
{
nodes.push(pNode);
pNode = pNode->next;
}
while (!nodes.empty())
{
pNode = nodes.top();
printf("%d\t", pNode->value);
nodes.pop();
}
}
![](https://i-blog.csdnimg.cn/blog_migrate/3d3c901a10c5e6d2480350ab52a7bed9.png)
/用递归实现
void PrintListReversingly_Recursively(ListNode* pHead)
{
if (pHead != NULL)
{
if (pHead->next != NULL)
{
PrintListReversingly_Recursively(pHead->next);
}
printf("%d\t", pHead->value);
}
代码(牛客网)
struct ListNode
{
int val;
struct ListNode *next;
ListNode(int x) :val(x), next(NULL)
{
}
};
class Solution {
public:
//method 1:iteratively
/*vector<int> printListFromTailToHead(ListNode* head)
{
vector<int> tailToHead;
if(head != NULL)
{
stack<ListNode*> headToTail;
ListNode *pNode = head;
while(pNode != NULL)
{
headToTail.push(pNode);
pNode = pNode->next;
}
while(!headToTail.empty())
{
tailToHead.push_back(headToTail.top()->val);
headToTail.pop();
}
}
return tailToHead;
}*/
//method 2:recursivly
vector<int> tailToHead;
vector<int> printListFromTailToHead(ListNode* head)
{
if(head != NULL)
{
if(head->next != NULL)
{
printListFromTailToHead(head->next);
}
tailToHead.push_back(head->val);
}
return tailToHead;
}
};