package com.lxg.algorithm;
public class Solution08 {
/**
* @param head: a ListNode
* @return: a ListNode
*/
public static ListNode swapPairs(ListNode head) {
// write your code here
ListNode temp= head;
int v;
while (temp != null && temp.next != null) {
v = temp.val;
temp.val = temp.next.val;
temp.next.val = v;
temp = temp.next.next;
}
return head;
}
public static void main(String[] args) {
ListNode head = new ListNode(0);
ListNode e1 = new ListNode(1);
ListNode e2 = new ListNode(2);
ListNode e3 = new ListNode(3);
ListNode e4 = new ListNode(4);
ListNode e5 = new ListNode(5);
head.next = e1;
e1.next = e2;
e2.next = e3;
e3.next = e4;
//e4.next = e5;
ListNode t = swapPairs(head);
while (t!= null) {
System.out.println(t.val);
t = t.next;
}
}
}
给一个链表,两两交换其中的节点,然后返回交换后的链表。
最新推荐文章于 2022-04-19 16:02:01 发布