题解 | #重排链表#

重排链表

https://www.nowcoder.com/practice/3d281dc0b3704347846a110bf561ef6b?tpId=117&tqId=37712&rp=1&ru=/exam/oj&qru=/exam/oj&sourceUrl=%2Fexam%2Foj%3Fpage%3D1%26pageSize%3D50%26search%3D%26tab%3D%25E7%25AE%2597%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D117&difficulty=undefined&judgeStatus=undefined&tags=&title=

无语,今晚牛客是不是抽风了

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    void reorderList(ListNode *head) {
      if (head == nullptr || head->next == nullptr) {
        return ;
      }
      
      //  利用快慢指针移动到中间,翻转后半段链表,然后合并两段链表
      ListNode *fast, *slow;
      fast = slow = head;
      
      //  slow 走到中间位置
      while (fast->next && fast->next->next) {
        fast = fast->next->next;
        slow = slow->next;
      }
      
      
      ListNode *pre = nullptr, *cur = slow->next, *nex = slow->next->next;
      
      //  断开链接
      slow->next = nullptr;
      
      while (nex) {
        cur->next = pre;
        pre = cur;
        cur = nex;
        nex = nex->next;
      }
      
      cur->next = pre;
      
      ListNode *head1 = head, *head2 = cur;
      
      while (head1 && head2) {
        ListNode *nex1 = head1->next;
        ListNode *nex2 = head2->next;
        head1->next = head2;
        head2->next = nex1;
        head1 = nex1;
        head2 = nex2;
      }
    }
};
全部评论

相关推荐

2024-12-08 18:59
东北大学 Java
Java抽象带篮子:外卖项目可以看看我的详细的外卖话术,里面还写了怎么描述项目,还为了提高含金量额外增加了很多技术亮点呢。另外我这边还有个7000多字的轮子项目话术,可以狠狠的速成,需要的似我
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务