两两交换链表中的节点
标题描述:给定一个链表,成对交换相邻节点,返回交换后的链表。不能只改变节点的内部值,需要实际交换节点。
见LeetCode官网示例。
资料来源:LeetCode
链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs/
版权归领扣网所有。商业转载请联系官方授权,非商业转载请注明出处。
00-1010首先,如果head为空或者head没有后继节点,直接返回head;然后,使用第一和第二两个指针分别指向第一和第二节点,并且新的前节点指向第一个。操作过程如下:第一个的下一个指向第二个的下一个;倒数第二个指向第一个;倒数第二;前几步是交换第一和第二的位置;然后先预分;接下来;指向第一个;然后进行下一次遍历,条件是第一个不为空,第一个的下一个不为空,直到这个条件无效,遍历结束。返回结果。公共类LeetCode _ 024 {
公共静态列表节点交换列表(列表节点头){ 0
if(head==null | | head . next==null){ 0
返回头;
}
ListNode newHead=head.next
ListNode pre=new ListNode(-1),first=head,second
pre.next=head
while(第一!=null first.next!=null){ 0
second=first.next
first . next=second . next;
second.next=first
pre.next=秒;
pre=first
first=first.next
}
返回newHead
}
公共静态void main(String[]args){ 0
ListNode head=new ListNode(1);
head . next=new ListNode(2);
head . next . next=new ListNode(3);
head . next . next . next=new ListNode(4);
head . next . next . next . next . next=new ListNode(5);
ListNode结果=swapPairs(head);
while(结果!=null){ 0
system . out . print(result . val ' ');
result=result.next
}
}
}【每日寄语】宇宙间浪漫的山川,生命的温暖,都值得你去进步。