Given a linked list, swap every, 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. 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 classSolution {Ten PublicListNode Swappairs (ListNode head) { One if(Head = =NULL|| Head.next = =NULL)returnhead; AListNode res =NewListNode (0); -ListNode pre =NewListNode (0); -Res.next =head; the BooleanIsfirst =true;//Flag whether the first time the head is processed, then point the res to the first node. - while(Head! =NULL&& Head.next! =NULL){ -Pre.next =Head.next; -Head.next =Pre.next.next; +Pre.next.next =head; - if(isfirst) { +Res.next =Pre.next; AIsfirst =false; at } -Pre =Pre.next.next; -Head =Head.next; - } - returnRes.next; - } in}
The topic seems to require not change the value of the node, so only by changing the point of the next to deal with, as long as the paper to draw a good chain of disassembly process.
Swap Nodes in Pairs Java solutions