您的位置:首页 > 其它

链表翻转:给出一个链表和一个数k,链表前k个节点进行翻转

2017-07-25 13:33 375 查看
问题描述:

给出一个链表和一个数k,比如链表1→2→3→4→5→6,k = 2,翻转后2→1→4→3→6→5,若k = 3, 翻转后3→2→1→6→5→4,若k = 4,翻转后4→3→2→1→5→6。

这是一道美团网的现在上面是题,下面有个人的做法,对大家进行讲解,程序猿最直接的自然是代码,话不多说先上代码:

#include<iostream>
#include<stdlib.h>
using namespace std;

struct ListNode
{
int _data;
ListNode* _next;

ListNode(int x = 0)
:_data(x)
, _next(NULL)
{}
};

typedef ListNode Node;

Node* createList(int* arr, int length) {
Node* pHead = NULL;
Node* pTemp, *pNode;
pTemp = NULL;
for (int i = 0; i < length; i++) {
pNode = (Node*)malloc(sizeof(Node));
pNode->_data = arr[i];
pNode->_next = NULL;
if (NULL == pHead)
pHead = pNode;
else
pTemp->_next = pNode;
pTemp = pNode;
}
return pHead;
}

void destroyList(Node* pHead) {
Node* pNode;
while (pHead) {
pNode = pHead;
pHead = pHead->_next;
free(pNode);
}
}

void PrintfList(Node* head)
{
Node* phead = head;
while (phead)
{
cout << phead->_data << " ";
phead = phead->_next;
}
cout << endl;
}

Node* reverseList(Node* pHead) {
if (NULL == pHead || NULL == pHead->_next)
return pHead;
Node* pNode;
Node* pNewHead = NULL;
while (pHead) {
pNode = pHead;
pHead = pHead->_next;
pNode->_next = pNewHead;
pNewHead = pNode;
}
return pNewHead;
}

Node* getLastNode(Node* pHead) {
while (NULL != pHead->_next)
pHead = pHead->_next;
return pHead;
}

Node* swapListByK(Node* pHead, int k) {
if (k <= 1)
return pHead;
int pos;
Node* pNode = pHead;
Node* pNewHead;
Node* pNextNode;
Node* pLastNode = NULL;;
pHead = NULL;
while (pNode) {
pos = 0;
pNewHead = pNode;
while (pNode && pos < k - 1) {
pNode = pNode->_next;
pos++;
}
if (pNode) {
pNextNode = pNode->_next;
pNode->_next = NULL;
if (NULL != pLastNode) {
pLastNode->_next = NULL;
}
pNewHead = reverseList(pNewHead);
if (NULL == pHead) {
pHead = pNewHead;
}
else {
pLastNode->_next = pNewHead;
}
pNode = getLastNode(pNewHead);
pNode->_next = pNextNode;
pLastNode = pNode;
pNode = pNextNode;
}
else {
break;
}
}
return pHead;
}

int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int length = sizeof(arr) / sizeof(arr[0]);
Node* pHead = createList(arr, length);
pHead = swapListByK(pHead, 2);
PrintfList(pHead);
destroyList(pHead);
system("pause");
return 0;
}


解题思路在于每一个变换节点指向的保存,翻转次数的确定,通过循环,两者之间相互交替工作,完成任务。循环变量的控制,就是翻转次数k,每完成一次k=k-1,当k<0时,退出循环。

首先要有新的链表的头指针,以及没有旋转部分的头指针,旋转部分的最后一个节点的指针,这是最重要的三部分,还有就是旋转过程中的中间变量。将旋转动作单独封装为一个动作,进行调用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐