- 题目描述
输入一个链表,从尾到头打印链表每个节点的值。
class Solution {
public:
vector<int> ret; //保存链表值
vector<int> printListFromTailToHead(ListNode* head) {
fun(head); //递归
return ret;
}
//递归函数,遇到链表结尾开始回溯;
void fun(ListNode* node)
{
if(node == NULL)
return;
fun(node->next);
ret.push_back(node->val);
}
};
2 . 题目描述
输入一个链表,输出该链表中倒数第k个结点。
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
//快慢指针,快指针先走K步;
class Solution {
public:
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
if(pListHead == NULL)
return NULL;
ListNode* node = pListHead;
while(k--)
{
if(node == NULL)
return NULL;
node = node->next;
}
while(node)
{
pListHead = pListHead->next;
node = node->next;
}
return pListHead;
}
};
3 . 题目描述
输入一个链表,反转链表后,输出链表的所有元素。
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
//递归,类似第一题的递归,然后回溯的时候修改指针
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
ListNode* pre = NULL;
return fun(pre,pHead);
}
ListNode* fun(ListNode* pre, ListNode* node)
{