Given a linked list, swap every two adjacent nodes and return its head.
Example:
Given1->2->3->4, you should return the list as2->1->4->3.
Note:
- Your algorithm should use only constant extra space.
- You may not modify the values in the list's nodes, only nodes itself may be changed.
/**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 p1=head;
ListNode p2=head.next;
while(p2!=null){
int t=p2.val;
p2.val=p1.val;
p1.val=t;
if(p1.next!=null&&p1.next.next!=null)
{p1=p1.next.next;
}else
break;
if(p2.next!=null&&p2.next.next!=null)
{p2=p2.next.next;}
else
break;
}
return head;
}
}递归方法
class Solution {
public ListNode swapPairs(ListNode head) {
if(head==null||head.next==null)
return head;
ListNode p1=head.next;
ListNode p2=p1.next;
p1.next=head;
head.next=swapPairs(p2);
return p1;
}
}
本文介绍了一种链表中相邻节点的交换算法,并提供了两种实现方法:迭代和递归。该算法只使用常数额外空间,不对节点值进行修改,仅变更节点连接。通过具体示例展示了如何将链表1->2->3->4转换为2->1->4->3。
526

被折叠的 条评论
为什么被折叠?



