24. Swap Nodes in Pairs

来源:互联网 发布:淘宝banner小图标 编辑:程序博客网 时间:2024/06/10 12:02

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

问题分析:
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;}

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

原创粉丝点击