第二章 链表 part02

发布时间 2023-12-03 00:00:51作者: 晴夜空

第二章 链表**part02**

24. 两两交换链表中的节点

 

Code

 

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode() : val(0), next(nullptr) {}
*     ListNode(int x) : val(x), next(nullptr) {}
*     ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
   ListNode* swapPairs(ListNode* head) {

       // (相对)“ 核心 区”

       


       if(head == NULL)            // 分 情况     /   划分 情况
      {
           return NULL;

      }else
       if(head->next == NULL)
      {
           return head;

      }else
       if(head->next != NULL)
      {
           ListNode* spear = head->next->next;
           ListNode* p = head;

           //cout<<"head->val : "<<head->val<<endl;
           //cout<<"head->next ->val : "<<head->next ->val<<endl;

           ListNode* pre ;

           //**   pre 处理 位   , 没有 更 靠 前 的 了

           pre = p ;

           p->next ->next = p ;

           head = p->next;

           p->next = spear ;

           p = spear ;

           

           // 注意 不要 忘了 更新 头结点

       

           do
          {
               
               if(p == NULL)
              {
                   return head;

               // swapPairs 链表 处理 将要 结束
              }else
               if(p->next == NULL)
              {
                   return head;
              }else
               if(p->next != NULL)
              {
                   spear = p->next->next;
                   pre->next = p->next;

                   pre = p;

                   p->next ->next = p;

                   p->next = spear;

                   p = spear ;               // 注意 不要 忘了 更新 " p "


              }

          }while(p != NULL );


           return head;


      }

       return NULL;                //return head;

  }
};