给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

示例:

    给定 1->2->3->4, 你应该返回 2->1->4->3.

1 /**
2  * 列表定义
3  * public class ListNode {
4  *     int val;
5  *     ListNode next;
6  *     ListNode(int x) { val = x; }
7  * }
8  */

非递归解法:

 1 class Solution {
 2     public ListNode swapPairs(ListNode head) {
 3         ListNode pre = new ListNode(0);
 4         pre.next = head;
 5         ListNode temp = pre;
 6         while(temp.next != null && temp.next.next != null) {
 7             ListNode start = temp.next;
 8             ListNode end = temp.next.next;
 9             temp.next = end;
10             start.next = end.next;
11             end.next = start;
12             temp = start;
13         }
14         return pre.next;
15     }
16 }
View Code

递归解法:

 1 class Solution {
 2     public ListNode swapPairs(ListNode head) {
 3         if(head == null || head.next == null){
 4             return head;
 5         }
 6         ListNode next = head.next;
 7         head.next = swapPairs(next.next);
 8         next.next = head;
 9         return next;
10     }
11 }
View Code

递归解法理解:假设列表只有两个元素时,swapPairs(next.next)返回null,即head.next = nullnext.next = head,最后返回next节点,即交换完成。

有多个元素时,swapPairs(next.next)返回上次的next节点,重复以上过程,即交换完成。

 

内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!

相关课程