首页 > 代码库 > LeetCode:Swap Nodes in Pairs
LeetCode:Swap Nodes in Pairs
Given a linked list, swap every two adjacent nodes and return its head.
For example,
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.
这道题非常简单,如果n>=2,先把开始的2个结点交换,把head指向开头。
之后只要后面有2个结点,就交换,其关键是2个结点的前一个结点和后一个结点,前一个结点要指向交换后的第一个结点,2个结点交换后的第2个结点要指向他们的后一个结点。其他没有什么。
public class Solution {
public ListNode swapPairs(ListNode head) {
if(head==null||head.next == null)return head;
ListNode start = head;
ListNode temp = start;
start = start.next;
ListNode next = start.next;
start.next = temp;
temp.next = next;
head = start;
start = next;
ListNode former = temp;
while(start!=null&&start.next!=null)
{
swap(former,start);
former = start;
start = start.next;
}
return head;
}
public void swap(ListNode former,ListNode node)
{
if(node==null||node.next==null)return;
else
{
ListNode temp = node;
node = node.next;
ListNode next = node.next;
former.next=node;
node.next = temp;
temp.next =next;
}
}
}