题目描述:给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例一
给定 1->2->3->4, 你应该返回 2->1->4->3.
示例二
给定 1->2->5->3->4,返回2->1->3->5->4
题目中要求是两两交换相邻的节点,每一次交换的操作都是一样的,所以我们可以想到递归,不断的调用自身函数
方法一:
递归
算法流程
- 从链表的头结点开始递归
- 每一次递归都交换一对节点,定义first和second来表示
- 下一次递归则是传递下一对需要交换的节点。若链表中还有节点,则继续递归
- 交换两个节点以后,返回second,因为这是交换后的新头节点
- 最后返回头结点,此时的头结点就是原始链表的第二个节点
java实现
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
if(head==null||head.next==null)
return head;
ListNode first=head;
ListNode second=head.next;
first.next=swapPairs(second.next);
second.next=first;
return second;
}
}
方法二:
迭代
题解可参考
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummy=new ListNode(0);
dummy.next=head;
ListNode prenode=dummy;
while(head!=null&&head.next!=null)
{
ListNode first=head;
ListNode second=head.next;
prenode.next=second;
first.next=second.next;
second.next=first;
prenode=first;
head=first.next;
}
return dummy.next;
}
}