题目:
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed
思路:
三个指针
Code1:
public ListNode swapPairs(ListNode head) {
if(head==null || head.next==null) return head;
ListNode cur=head, post=cur.next;
cur.next=post.next;
post.next=cur;
head=post;
ListNode pre=cur;
cur=cur.next;
while(cur!=null && post!=null){
post=cur.next;
if(post!=null){
pre.next=post;
cur.next=post.next;
post.next=cur;
pre=cur;
cur=cur.next;
}else{
break;
}
}
return head;
}备注:
三个指针换
本文介绍了一种在常数空间复杂度下交换链表中每两个相邻节点的算法实现。通过使用三个指针进行迭代,该算法能在不修改节点值的情况下改变节点连接,最终返回变换后的链表头。

504

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



