https://leetcode.com/problems/swap-nodes-in-pairs/#/description
问题描述:将每两个相邻的结点交换
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.
不可以修改值。只能交换结点。
思路解析:设置两个指针,交换
代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode swapPairs(ListNode head) {
ListNode d=new ListNode(0);
d.next=head;
ListNode c=d;
while(c.next!=null && c.next.next!=null){
ListNode f=c.next;
ListNode s=c.next.next;
f.next=s.next;
s.next=f;
c.next=s;
c.next.next=f;
c=c.next.next;
}
return d.next;
}
}