链表结构:
#include <iostream>
using namespace std;
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
1.输入一个链表,输出该链表中倒数第k个结点。
//1.输入一个链表,输出该链表中倒数第k个结点
//一快一慢指针
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k)
{
if(!pListHead || k== 0)
return NULL;
ListNode* p_fast = pListHead;
ListNode* p_slow = pListHead;
// 快指针先往前走k个结点
for(int i = 0; i < k-1; i++)
{
if(p_fast->next)
p_fast = p_fast->next;
else
return NULL;
}
while(p_fast->next)
{
p_fast = p_fast->next;
p_slow = p_slow->next;
}
return p_slow;
}
2.输入一个链表,反转链表后,输出新链表的表头
ListNode* Reverse(ListNode* pListHead)
{
if(!pListHead)
return NULL;
//前中后3个指针 逐次将前中的指针反转
ListNode* pre = NULL;
ListNode* pnode = pListHead;
ListNode* pnext = pListHead->next;
while(pnode)
{
pnode->next = pre;
pre = pnode;
pnode = pnext;
pnext = pnext->next;
}
return pre;
}
3.3.输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
if(!pHead1)
return pHead2;
if(!phea2)
return pHead1;
ListNode* pMergeHead = NULL;
if(pHead1->val < pHea2->val)
{
pMergeHead = pHead1;
pMergeHead->next = Merge(pHead1->next, phea2);
}
else
{
pMergeHead = pHead2;
pMergeHead->next = Merge(pHead1, pHead2->next);
}
return pMergeHead;
}