一,输入一个链表,反转链表后,输出新链表的表头。
#include<stack>
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(NULL==pHead || NULL == pHead->next)
return pHead;
stack<ListNode *> stack;
ListNode * pNode = pHead;
while(pNode->next)
{
stack.push(pNode);
pNode = pNode->next;
}
ListNode * Head = pNode;
while(!stack.empty())
{
pNode->next = stack.top();
pNode = pNode->next;
stack.pop();
}
pNode->next = NULL;
return Head;
}
};
二,输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
#include<iostream>
#include<stdlib.h>
#include<vector>
#include<stack>
using namespace std;
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
stack<int> stack;
vector<int> ret;
ListNode *pNode = head;
if(pNode==NULL){
return ret;
}
while(pNode!=NULL)
{
stack.push(pNode->val);
pNode = pNode->next;
}
while(!stack.empty())
{
ret.push_back(stack.top());
stack.pop();
}
return ret;
}
};
三,输入一个链表,输出该链表中倒数第k个结点。
#include<cstdlib>
class Solution {
public:
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
if(NULL==pListHead || 0==k)
return NULL;
ListNode *first = pListHead;
ListNode *second = pListHead;
int i = 0;
while(i<k-1){
if(first->next)
{
first = first->next;
}
else
{
return NULL;
}
i++;
}
while(first->next)
{
first = first->next;
second = second->next;
}
return second;
}
};