Given a linked list, swap every two adjacent nodes and return its head.
Example:
Given1->2->3->4
, you should return the list as2->1->4->3
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
主要考察交换两个节点的顺序
从现在开始尝试所有代码都用Java写了!!!
/**
* 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&¤t.next.next!=null){
ListNode first=current.next;
ListNode second=current.next.next;
current.next=second;
first.next=second.next;
second.next=first;
current=current.next.next;
}
return dummy.next;
}
}