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.
Subscribe to see which companies asked this question
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 public ListNode swapPairs(ListNode head) { 11 if(head == null || head.next == null) return head; 12 ListNode res = new ListNode(0); 13 ListNode pre = new ListNode(0); 14 res.next = head; 15 boolean isfirst = true;//标志是否第一次处理head,是的话将res指向第一个节点。 16 while(head != null && head.next != null){ 17 pre.next = head.next; 18 head.next = pre.next.next; 19 pre.next.next = head; 20 if(isfirst){ 21 res.next = pre.next; 22 isfirst = false; 23 } 24 pre = pre.next.next; 25 head = head.next; 26 } 27 return res.next; 28 } 29 }
题目貌似要求不能改变节点的值,所以只能通过改变next 的指向来处理,只要在纸上画好链的拆解过程即可。