1. 对应力扣题目连接
2. 实现案例代码
public class ExchangeLinkedListsPairwise {
public static void main ( String [ ] args) {
ListNode head = new ListNode ( 1 ) ;
head. next = new ListNode ( 2 ) ;
head. next. next = new ListNode ( 3 ) ;
head. next. next. next = new ListNode ( 4 ) ;
ListNode swapPairsIterative = swapPairsIterative ( head) ;
printList ( swapPairsIterative) ;
}
public static ListNode swapPairsIterative ( ListNode head) {
ListNode dummy = new ListNode ( 0 ) ;
dummy. next = head;
ListNode prev = dummy;
while ( head != null && head. next != null ) {
ListNode firstNode = head;
ListNode secondNode = head. next;
prev. next = secondNode;
firstNode. next = secondNode. next;
secondNode. next = firstNode;
prev = firstNode;
head = firstNode. next;
}
return dummy. next;
}
public static void printList ( ListNode head) {
ListNode current = head;
while ( current != null ) {
System . out. print ( current. val + " " ) ;
current = current. next;
}
System . out. println ( ) ;
}
}
class ListNode {
public int val;
public ListNode next;
ListNode ( ) {
}
ListNode ( int val) {
this . val = val;
}
ListNode ( int val, ListNode next) {
this . val = val;
this . next = next;
}
}