题目
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
分析
给出一个链表,依次翻转K个元素,如果剩下的少于K个,保留原样。
可以借鉴栈的思想,依次压栈,移植出栈顺序正好相反,再组成一个链表返回即可。
注意测试数据中,出现了K大于链表长度的现象,直接返回即可。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseKGroup(struct ListNode* head, int k) {
struct ListNode * ans=NULL,*p=head;
int length=0;
while(p!=NULL)
{
p=p->next;
length++;
}
int num[10000]={0};
int i,j;
for(i=0;i<length/k;i++)
{
for(j=0;j<k;j++)
{
num[j]=head->val;
head=head->next;
}
for(j=k-1;j>=0;j--)
{
struct ListNode * temp=(struct ListNode *)malloc(sizeof(struct ListNode));
temp->val=num[j];
temp->next=NULL;
if(ans==NULL)
{
ans=temp;
p=temp;
}
else
{
p->next=temp;
p=p->next;
}
}
}
if(p!=NULL) p->next=head;
else return head;
return ans;
}