[LeetCode-interview algorithm classic-Java implementation] [024-Swap Nodes in Pairs (node of the paired exchange single-chain table)], leetcode -- java
[024-Swap Nodes in Pairs (node of the paired exchange single-chain table )][LeetCode-interview algorithm classic-Java implementation] [directory indexes for all questions]Original question
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given1->2->3->4
, You shoshould return the list2->1->4->3
.
Your algorithm shocould use only constant space. You may not modify the values in the list, only nodes itself can be changed.
Theme
Given a single-chain table, two adjacent nodes are exchanged in pairs. The algorithm method should be used as a constant auxiliary space. The value of the node cannot be changed, but the node can only be exchanged.
Solutions
A head node root is used to assist in operations. The linked list to be exchanged is exchanged for each two locations, and the exchanged nodes are connected to the root linked list, until all nodes are processed.
Code Implementation
Node class
public class ListNode { int val; ListNode next; ListNode(int x) { val = x; next = null; }}
Algorithm Implementation class
Public class Solution {public ListNode swapPairs (ListNode head) {ListNode node = new ListNode (0); // header node. next = head; // p points to the End node of the new linked list ListNode p = node; ListNode tmp; // each two perform operations while (p. next! = Null & p. next. next! = Null) {// record the location for processing next time tmp = p. next. next; // The following three sentences are used to complete two node exchanges. next. next = tmp. next; tmp. next = p. next; p. next = tmp; // point to the new end node p = tmp of the returned linked list. next;} head = node. next; node. next = null; return head ;}}
Evaluation Result
Click the image. If you do not release the image, drag it to a position. After the image is released, you can view the complete image in the new window.
Note
Please refer to the following link for more information: http://blog.csdn.net/derrantcm/article/details/47034975]
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.