题目:
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例:
输入:1->2->3->4
输出:2->1->4->3
代码:
public class Test7 {
@Test
public void test(){
ListNode node1 = new ListNode(1);
ListNode node2 = new ListNode(2);
ListNode node3 = new ListNode(3);
ListNode node4 = new ListNode(4);
node1.next=node2;
node2.next=node3;
node3.next=node4;
new Test7().swapPairs(node1);
}
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
public ListNode swapPairs(ListNode head) {
if (head==null || head.next==null) {
return head;
}
ListNode next =head.next;
ListNode now = head;
ListNode result = head.next;
now.next = next.next;
next.next = now;
function(now.next,now);
return result;
}
public static void function(ListNode now,ListNode before){
if(now==null || now.next == null){
return ;
}
ListNode next = now.next;
now.next = next.next;
next.next = now;
before.next=next;
function(now.next,now);
}
}