欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

24. Swap Nodes in Pairs

程序员文章站 2022-07-14 08:25:33
...

问题描述:
24. Swap Nodes in Pairs

问题分析:
1)这道题属于链表操作的题目,思路比较清晰,每次跳两个节点
2)这道题中用了一个辅助指针作为表头,这是链表中比较常用的小技巧,因为这样可以避免处理head的边界情况,一般来说要求的结果表头会有变化的会经常用这个技巧

图解分析:
①初始化:
24. Swap Nodes in Pairs

②first.next=second.next
24. Swap Nodes in Pairs

③current.next=second
24. Swap Nodes in Pairs

④current.next.next=first
24. Swap Nodes in Pairs

⑤current = current.next.next
24. Swap Nodes in Pairs

JAVA代码展示:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
          ListNode dummy = new ListNode(0);
          dummy.next = head;
          ListNode current = dummy;

          while (current.next != null && current.next.next != null) {
              ListNode first = current.next;
              ListNode second = current.next.next;
              first.next = second.next;
              current.next = second;
              current.next.next = first;
              current = current.next.next;
          }
          return dummy.next;

    }
}

运行图片展示:
24. Swap Nodes in Pairs

C语言描述:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* swapPairs(struct ListNode* head) {
      if(head ==NULL)  
        return NULL; 

      struct ListNode *dummy = (struct ListNode*)malloc(sizeof(struct ListNode));
      dummy->next = head;

      struct ListNode *current = dummy;

      while(current->next!=NULL && current->next->next!=NULL){
         struct ListNode *ptr1 = head;
         struct ListNode *ptr2 = head->next;


          ptr1->next = ptr2->next;
          current->next =ptr2;
          current->next->next = ptr1;
          current=current->next->next;
      }

      return current->next;

}

运行图片展示:
24. Swap Nodes in Pairs