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.
这个题主要还是练习指针的修改。这里需要注意的一个问题是,当1和2的指针方向修改后。1需要指向第3个数,但实际上,1不应该指向3,而是应该指向4,因为下一轮循环中3和4的指针也要交换,因此我们用一个tmp指针来处理这个问题。
/**
* 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 *p, *q, *tmp;
if(!head || !head -> next)
return head;
else{
p=head;
q=head->next;
head=q;
tmp=p;
while(p && q){
tmp->next=q; //修改交换后的下一跳
p->next=q->next;
q->next=p;
tmp=p; //保存p的上一个位置
p=p->next;
if(p != NULL)
q=p->next;
}
return head;
}
}
};
Given a linked list, reverse the nodes of a linked list k at a time and return its modified 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
这个问题是上个问题的升级,难点在于需要反序的链表段变成了k个,是一个变量。在处理问题时,先把链表的反序作为一个子程序来处理。在主程序中,就是要判断出需要反序的段,而且要处理好头尾指针的方向。需要注意的是:1.结果的头指针位置第一个反序段的原序列的末尾;2.前一个反序段结果的末尾要指向下一个反序段的原序列的末尾。3.每一次开始统计反序段的时候,反序段头尾指针要一致。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void resort(ListNode *ph, ListNode *pe){ //链表反序
ListNode *f=ph, *s=f->next;
ListNode *tmp;
while(s!=pe) {
tmp=s->next;
s->next =f;
f=s;
s=tmp;
}
s->next=f;
}
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode *ph=head,*pe=head,*result = head,*l=head,*tmp;
int count = 1;
if(!head || !head->next)
return head;
if(k==1)
return head;
while(pe -> next){
pe = pe -> next;
count++;
if(count%k==0){
tmp=pe->next;
if(count==k) //结果head位置
result=pe;
if(count>k){ //处理每个反序段之间的衔接
l->next=pe;
l=ph;
}
resort(ph,pe);
ph->next=tmp;
if(tmp){ //进行下一轮反序段累加前,头尾指针要一致
ph=tmp;
pe=tmp;
count++;//相当于尾指针+1,因此,此时count要随之+1
}
}
}
return result;
}
};