例如:1->2->3->4->null
变成:2->1->4->3->null
/**
java的两个两个的交换链表中的数据节点。
*/
public class ExchangeNode5 {
static class ListNode {
int val;
ListNode next;
public ListNode() {}
public ListNode(int x) {val = x;}
}
public static ListNode exchange(ListNode head) {
if(head==null||head.next==null) {
return head;
}
ListNode ans = head;
ListNode temp = ans.next;
// 下面是递归的调用的写法
ListNode temp2 = exchange(temp.next);
ans.next = temp2;
temp.next = ans;
return temp;
}
public static void main(String[] args) {
ListNode n1 = new ListNode(1);
ListNode n2 = new ListNode(2);
ListNode n3 = new ListNode(3);
ListNode n4 = new ListNode(4);
n1.next = n2;
n2.next = n3;
n3.next = n4;
n4.next = null;
ListNode res = exchange(n1);
while (res!=null) {
System.out.println(res.val);
res = res.next;
}
}
}