24. Swap Nodes in Pairs
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4
, you should return the list as 2->1->4->3
.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head)
{
ListNode hhhead(-1);
hhhead.next = head;
ListNode *last = &hhhead;
ListNode *p = head;
ListNode *q;
if (p)
q = p->next;
while (p && q)
{
last->next = q;
p->next = q->next;
q->next = p;
last = p;
p = p->next;
if (p)
q = p->next;
}
return hhhead.next;
}
};
25. Reverse Nodes in k-Group
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For example,
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 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 {
public:
ListNode* reverse(ListNode *k1, ListNode *k2, int k)
{
int i = 1;
ListNode *p;
while(i < k)
{
p = k1->next;
k1->next = p->next;
p->next = k2->next;
k2->next = p;
i++;
}
for (i = 0; i < k; i++)
k1 = k1->next;
return k1;
}
ListNode* reverseKGroup(ListNode* head, int k)
{
if(!head)
return head;
ListNode hhead(-1);
hhead.next = head;
ListNode *k1 = &hhead;
ListNode *k2;
while (1)
{
k2 = k1;
int i = 1;
while (i <= k)
{
k2 = k2->next;
if (!k2)
return hhead.next;
i++;
}
k1 = reverse(k1, k2, k);
}
return hhead.next;
}
};