题解:
需要注意的是本题是没有头结点的(被坑了)
- 先找到链表的中间点:通过设置p,q两个指针,p每次走一步,q每次走两步
- 将后半部分链表反转
- 将链表按题目要求合并
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void rearrangedList(ListNode* head) {
ListNode *p = head,*q = head->next;
while(q->next != NULL)
{
p = p->next;
q = q->next;
if(q->next) q = q->next; //q走两步
} //走完之后,p所指的就是中间结点
q = p->next; //指向后半段的首结点
p->next = NULL;
ListNode *pre = NULL,*next; //这里使用两个辅助指针来使后面的链表逆置
while(q != NULL)
{
next = q->next;
q->next = pre;
pre = q;
q = next;
} //注意 最后是pre指向反转后的第一个结点(即an)
q = pre;
p = head;
ListNode *qpre;
while(q != NULL)
{
pre = p;
qpre = q;
p = p->next;
q = q->next;
pre->next = qpre;
qpre->next = p;
}
}
};