题目:k个一组翻转链表
题目描述:
给出一个链表,每 k 个节点一组进行翻转,并返回翻转后的链表。
k 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍,那么将最后剩余节点保持原有顺序。
示例 :
给定这个链表:1->2->3->4->5
当 k = 2 时,应当返回: 2->1->4->3->5
当 k = 3 时,应当返回: 3->2->1->4->5
说明 :
你的算法只能使用常数的额外空间。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
网址:https://leetcode-cn.com/problems/reverse-nodes-in-k-group/
解题思路:
- 使用栈存储k个数据,每存储 st.size() == k ,则进行一次反转;
- 每次循环要记录返回的链表的最后一个节点 nextline , 为了链接下一个反转的首节点;
- 当st.size() < k 时,则将nextline->next = st 中的最下面的元素;
class Solution {
public:
ListNode* reverseKGroup(ListNode* tmp, int k) {
stack<ListNode *> st ;
ListNode* nextline = NULL ;
ListNode* ret = tmp ;
ListNode* nexttmp = NULL ;
bool sta = true ;
while (tmp)
{
st.push(tmp) ;
tmp = tmp->next ;
if (st.size() == k)
{
if (sta)
{
ret = st.top() ;
sta = false ;
}
else
nextline->next = st.top() ;
nexttmp = st.top() ;
st.pop() ;
while(! st.empty())
{
nexttmp->next = st.top() ;
nexttmp = nexttmp->next ;
nexttmp->next = NULL ;
st.pop() ;
}
nextline = nexttmp ;
}
}
while (! st.empty())
{
if (! nextline)
break ;
nextline->next = st.top() ;
st.pop() ;
}
return ret ;
}
};