Problem Description:
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.
Problem Analysis:
Each cycle of the pointer transformation, such as: In addition to the order of C and D, but also note that the last cycle of the tail node of the pre is on the way to a, whose next is currently pointing to C, it should point to the flipped D;
Code:
/** * Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode ( int x) {val = x;} *} * / Public class solution { PublicListNodeSwappairs(ListNode head) {if(Head = =NULL|| Head.next = =NULL)returnHead ListNode result = Head.next; ListNode Prenode =NULL;//Tail node of previous loopListNode anode =NULL;//The left node of the loopListNode BNode =NULL;//Right node of the loop while(Head! =NULL&& Head.next! =NULL) {anode = head; BNode = Head.next;//prepare for the next cyclehead = Bnode.next;if(Prenode! =NULL) Prenode.next = BNode;//To point the previous loop tail node to the head node after the loop is flippedPrenode = anode;//Flip A, bAnode.next = Bnode.next; Bnode.next = anode; }returnResult }}
leetcode-24 Swap Nodes in Pairs