LeetCode24 Swap Nodes in Pairs pair exchange linked list node, leetcode24 exchange chain

Source: Internet
Author: User

LeetCode24 Swap Nodes in Pairs pair exchange linked list node, leetcode24 exchange chain

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.

Translation:

A linked list is provided to exchange two connected nodes.

Ideas:

It is a node exchange problem. You only need to save the header node and clarify the location of the switch node.

Code:

Public ListNode swapPairs (ListNode head) {ListNode root = new ListNode (0); // create a first node pointing to the linked list and start root. next = head; ListNode pre = root; // The previous node while (head! = Null & head. next! = Null) {ListNode t = head. next. next; pre. next = head. next; pre. next. next = head; head. next = t; pre = head; head = t;} return root. next ;}


Ensure that the node and the next node exist.

Then there is the exchange problem. Suppose the current linked list is 1-> 2-> 3-> 4. First, create a root node, whose next points to the header.

First cycle: pre points to root, head points to 1, to switch 12, first save the next node 3 of 2, represented by t, then make the next Of pre 2 2, that is, the next node of head; the next node of next 2 is 1, so the result is pre. next. next = head. the next part of the last head is 3, that is, head. next = t.

At this time, the linked list is 2-1-3-4. At this time, the pointer jumps 2. That is, pre points to 1 and head points to 3. Then, the system proceeds to realize the exchange in a loop.








Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.