给出一个链表,每 k 个节点一组进行翻转,并返回翻转后的链表。
k 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍,那么将最后剩余节点保持原有顺序。
示例 :
给定这个链表:1->2->3->4->5
当 k = 2 时,应当返回: 2->1->4->3->5
当 k = 3 时,应当返回: 3->2->1->4->5
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
/* 翻转一组节点,返回值是翻转后的最后一个节点 */
ListNode *reverseOneGroup(ListNode *pHead, int k)
{
ListNode *pre = pHead;
ListNode *p1 = pre->next;
ListNode *p2 = p1->next;
k -= 1;
while(k > 0)
{
ListNode *pTemp = p2->next;
p2->next = p1;
p1 = p2;
p2 = pTemp;
k--;
}
ListNode *pTail = pre->next; //返回值即为下一个要翻转链表区间头结点的前一个节点
pre->next->next = p2;
pre->next = p1;
return pTail;
}
public:
ListNode* reverseKGroup(ListNode* head, int k) {
if(NULL == head || NULL == head->next) return head;
ListNode *pHead = new ListNode (0);
ListNode *pNode = pHead;
pHead->next = head;
int len = 0;
while(head)
{
len++; //获取链表长度
head = head->next;
}
int group = len / k; //获取组数目
for(int i = 0; i < group; i++)
{
pNode = reverseOneGroup(pNode, k); //循环调用
}
return pHead->next;
}
};
总结了一部分链表的翻转方法,代码如下:
ListNode *reverseList(ListNode *head)
{
//就地翻转
ListNode *pHead = new ListNode(0);
pHead->next = head;
ListNode *pPre = pHead;
ListNode *pCur = head;
while(pCur->next)
{
pPre->next = pCur->next;
pCur->next = pCur->next->next;
pPre->next->next = pCur;
}
return pHead->next;
}
ListNode *reverseList(ListNode *head)
{
//前插法
ListNode *pHead = new ListNode(0);
ListNode *pCur = head;
while(pCur)
{
ListNode *pNext = pCur->next;
pCur->next = pHead->next;
pHead->next = pCur;
pCur = pNext;
}
return pHead->next;
}
//方法同就地翻转,更易理解一点
ListNode reverseList(ListNode *head)
{
if(NULL == head || NULL == head->next) return head;
ListNode *pHead = new ListNode (0);
pHead->next = head;
ListNode *pre = pHead;
ListNode *p1 = pre->next;
ListNode *p2 = p1->next;
while(p2)
{
ListNode *pTemp = p2->next;
p2->next = p1;
p1 = p2;
p2 = pTemp;
}
pre->next->next = p2;
pre->next = p1;
return pHead->next;
}