1. 题⽬链接:24.两两交换链表中的节点
2. 题⽬描述:
3. 解法(模拟):
算法思路:
画图画图画图,重要的事情说三遍~
C++算法代码:
/**
* 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==nullptr||head->next==nullptr)
{
return head;
}
//虚拟头结点
ListNode* xn_head=new ListNode(0);
xn_head->next=head;
//设置四个指针
ListNode* yi=xn_head,*er=yi->next,*san=er->next,*si=san->next;
//两个元素都存在才可以交换
while(er&&san)
{
//进行交换指针
yi->next=san;
san->next=er;
er->next=si;
//恢复指针
yi=er;
er=si;
//当指针存在时设置后续指针
if(er)
{
san=er->next;
}
if(san)
{
si=san->next;
}
}
san=xn_head->next;
delete(xn_head);
return san;
}
};
Java算法代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution
{
public ListNode swapPairs(ListNode head)
{
if (head == null || head.next == null) return head;
ListNode newHead = new ListNode(0);
newHead.next = head;
ListNode prev = newHead, cur = prev.next, next = cur.next, nnext =
next.next;
while (cur != null && next != null)
{
// 交换节点
prev.next = next;
next.next = cur;
cur.next = nnext;
// 修改指针
prev = cur; // 注意顺序
cur = nnext;
if (cur != null) next = cur.next;
if (next != null) nnext = next.next;
}
return newHead.next;
}
}