题目:
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.
Java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode swapPairs(ListNode head) {
if(head==null||head.next==null) return head;
ListNode pre = new ListNode(0); ListNode dummy = pre, cur = head, post = cur.next;
pre.next = head;
while(post!=null){
cur.next = post.next;
post.next = cur;
pre.next = post;
pre = cur;
cur = cur.next;
if(cur==null) break;
post = cur.next;
}
return dummy.next;
}
}
Python
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
dup=ListNode(0); dup.next=head;p=dup
while p.next!=None and p.next.next!=None:
temp=p.next
p.next=temp.next
p=p.next
temp.next=p.next
p.next=temp
#关键
p=temp
return dup.next