对于链表,我感觉我悟了。。。
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*
* C语言声明定义全局变量请加上static,防止重复定义
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
struct ListNode* reverseKGroup(struct ListNode* head, int k ) {
// write code here
int n = 0; //节点数
//判断在哪个节点翻转
if (head == NULL || head->next == NULL)
{
return head;
}
struct ListNode* pn; //判读链表的节点数
pn = head;
while (pn != NULL)
{
pn = pn->next;
n = n+1; //节点数为n
}
if (n<k) //节点数小于k
{
return head;
}
struct ListNode* p0;
struct ListNode* p1; //定义需要连接的首尾指针
struct ListNode* p2;
p0 = NULL;
p1 = NULL;
p2 = NULL;
//反转函数:
struct ListNode* pre;
struct ListNode* cur;
struct ListNode* nex;
cur = head;
nex = cur->next;
pre = cur;
cur = nex;
for (int j=1;j<=(n/k);j++)
{
p0 = pre;
for(int i =1;i<k;i++) //做反转
{
nex = cur->next;
cur->next = pre;
pre = cur;
cur = nex;
}
p1 = pre;
if (j==1)
{
head = p1;
}
if (j>=2)
{
p2->next = p1; //首尾相连
p0->next = NULL;
}
p2 = p0;
nex = cur->next;
pre = cur;
cur = nex;
}
p2->next = pre;
return head;
}