Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given
Given
1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
每次操作两个节点, 并且要记录两个节点前边的一个节点prev
例如1-->2-->3-->4, 对于每次循环
对于3,4 节点 把3放到4后面, 然后把prev 2 指向4, 再记录3节点为prev
时间O(n) 空间O(1)
每次操作两个节点, 并且要记录两个节点前边的一个节点prev
例如1-->2-->3-->4, 对于每次循环
对于3,4 节点 把3放到4后面, 然后把prev 2 指向4, 再记录3节点为prev
时间O(n) 空间O(1)
public class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
ListNode node = head;
while (node != null && node.next != null) {
ListNode tem = node.next;
node.next = node.next.next;
tem.next = node;
pre.next = tem;
pre = node;
node = node.next;
}
return dummy.next;
}
}
没有评论:
发表评论