24. Swap Nodes in Pairs

问题描述:
这里写图片描述

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

图解分析:
①初始化:
这里写图片描述

②first.next=second.next
这里写图片描述

③current.next=second
这里写图片描述

④current.next.next=first
这里写图片描述

⑤current = current.next.next
这里写图片描述

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;

    }
}

运行图片展示:
这里写图片描述

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;

}

运行图片展示:
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值