24. Swap Nodes in Pairs
程序员文章站
2022-07-14 08:25:33
...
问题描述:
问题分析:
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;
}
运行图片展示:
推荐阅读
-
Leetcode 1530. Number of Good Leaf Nodes Pairs (python)
-
Leetcode——24. Swap Nodes in Pairs
-
24. Swap Nodes in Pairs
-
LeetCode 24. Swap Nodes in Pairs
-
LeetCode 24. Swap Nodes in Pairs
-
24. Swap Nodes in Pairs
-
24. Swap Nodes in Pairs。
-
leetcode 24. Swap Nodes in Pairs 每两个结点反转一次
-
Swap Nodes in Pairs
-
Swap Nodes in Pairs