赞
踩
输入:head = [1,2,3,4]
输出:[2,1,4,3]
head
表示原始链表的头节点,新的链表的第二个节点,用 newhead
表示新的链表的头节点,原始链表的第二个节点,则原始链表中的其余节点的头节点是 newhead.next
。令head.next=swappairs( newhead.next)
,表示将其余节点进行两两交換,交換后的新的头节点为head
的下ー个节点。然后令newhead.next=head
,即完成了所有节点的交換。最后返回新的链表的头节点 newhead
。package leetcodePlan.Base; import leetcodePlan.Base.P0082.ListNode; public class P0024 { public static void main(String[] args) { // TODO Auto-generated method stub } public ListNode swapPairs(ListNode head) { if(head == null || head.next == null){ return head ; } ListNode newHead = head.next ; head.next = swapPairs(newHead.next) ; newHead.next = head ; return newHead ; } public static class ListNode { int val; ListNode next; ListNode() {} ListNode(int val) { this.val = val; } ListNode(int val, ListNode next) { this.val = val; this.next = next; } } }
class Solution { public ListNode swapPairs(ListNode head) { ListNode dummyHead = new ListNode(0); dummyHead.next = head; ListNode temp = dummyHead; while (temp.next != null && temp.next.next != null) { ListNode node1 = temp.next; ListNode node2 = temp.next.next; temp.next = node2; node1.next = node2.next; node2.next = node1; temp = node1; } return dummyHead.next; } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。