逆置链表之前写过整条链表的逆置,今天在一本书上看到了关于k个节点的逆置。
关于k个节点的逆置有两个方法
方法一:利用栈来实现这个逆置,当进栈的个数达到了k个之后,就进行出栈操作,而当不足k个时,则直接连接在新链表的后面
方法二:记录链表的第一个位置,走k步之后记录尾节点,并记录尾节点的next,然后将尾节点的next置空,逆置这段新链表,以此类推 知道这段链表的结束。
代码实现如下:
//方法1:
Node* RotateList(Node* list, size_t k)
{
assert(list);
if (list==NULL && k <2 )
{
return list;
}
Node* cur = list;
Node* newList = cur;
stack<int> s;
int count = 0;
while (cur)
{
s.push(cur->_data);
cur = cur->_next;
++count;
if (count% k==0)
{
while (newList != cur)
{
newList->_data = s.top();
s.pop();
newList = newList->_next;
}
}
}
return list;
}
//方法2:
Node* Reverse(Node *head){
Node *now, *next;
if (head == NULL)
return NULL;
now = head->_next;
head->_next = NULL;
while (now != NULL){
next = now->_next;
now->_next = head;
head = now;
now = next;
}
return head;
}
Node* RotateList2(Node* list, size_t k)
{
assert(list);
if (list == NULL&&k < 2)
{
return list;
}
Node* cur = list;
Node* tmp = NULL;
Node* tail = NULL;
int count = 0;
while (cur)
{
++count;
if (count == k)
{
if (tail == NULL)
{
tmp = cur->_next;
cur->_next = NULL;
cur = tmp;
tmp = list;
list = Reverse(list);
tmp->_next = cur;
tail = tmp;
}
else
{
tmp = cur->_next;
cur->_next = NULL;
cur = tmp;
tmp = tail->_next;
tail->_next = Reverse(tmp);
tmp->_next = cur;
tail = tmp;
}
count = 0;
}
else
{
cur = cur->_next;
}
}
return list;
}
void test()
{
Node* s1 = NULL;
PushBack(&s1, 1);
PushBack(&s1, 2);
PushBack(&s1, 3);
PushBack(&s1, 4);
PushBack(&s1, 5);
PushBack(&s1, 6);
PrintList(s1);
Node* s = RotateList(s1,3);
PrintList(s);
Node* s = RotateList2(s1,3);
PrintList(s);
}