题目描述
Given a linked list, swap every two adjacent nodes and return its head.
Note:
- Your algorithm should use only constant extra space.
- You may not modify the values in the list's nodes, only nodes itself may be changed.
样例
Example:
Given1->2->3->4, you should return the list as2->1->4->3.
思路分析
头结点前增加一dummy结点,构造两个结点,first和second,依次交换两节点值即可
代码
/**
* 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;
}
}结果

链表节点交换算法
本文介绍了一种在链表中交换每两个相邻节点值的算法实现。通过在头结点前增设一个虚拟结点(dummy),并使用两个指针(first和second)来遍历链表,实现了节点值的有效交换。该算法仅使用常数额外空间,适用于需要改变节点自身而非节点值的情况。
116

被折叠的 条评论
为什么被折叠?



