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.1 public static LinkedListNode SwapNodesinPairs2(LinkedListNode head) 2 { 3 if (head == null || head.Next == null) 4 return head; 5 6 LinkedListNode fakehead = new LinkedListNode(); 7 fakehead.Next = head; 8 9 LinkedListNode l1 = head;10 LinkedListNode l2 = head;11 LinkedListNode prev = fakehead;12 LinkedListNode ret = head.Next;13 LinkedListNode next = head;14 15 while (next != null && next.Next != null)16 {17 l1 = next;18 l2 = next.Next;19 next = next.Next.Next;20 l2.Next = l1;21 l1.Next = next;22 prev.Next = l2;23 prev = l1;24 }25 26 return ret;27 }
代码分析:
看来我的总结是正确的,每遇到Linked List的题都在前面加个fakehead. 后面的逻辑就方便很多,不用判断这个那个。