Given a linked list, swap every two adjacent nodes and return its head.node
Example:spa
Given , you should return the list as .1->2->3->42->1->4->3
Note:code
交换链表中的节点,题目不难,须要细心,有两种解法。blog
1.递归,逻辑清晰。用临时节点保存交换中的中间节点,以防链表断裂,节点丢失。递归
class Solution { public ListNode swapPairs(ListNode head) { if (head == null || head.next == null) return head; ListNode temp = head.next; head.next = swapPairs(head.next.next); temp.next = head; return temp; } }
2.直接循环作,须要一个假的头节点来保存交换以后的头节点,一样须要临时节点保存交换中的中间节点。it
class Solution { public ListNode swapPairs(ListNode head) { if (head == null || head.next == null) return head; ListNode fakeHead = new ListNode(0), pre = fakeHead, temp = null; fakeHead.next = head; while (pre.next!=null && pre.next.next!=null) { temp = pre.next.next; pre.next.next = temp.next; temp.next = pre.next; pre.next = temp; pre = temp.next; } return fakeHead.next; } }
在LeetCode上循环比递归耗时减小1msio