Leetcode -- Swap nodes in pairs

Source: Internet
Author: User

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.

Original question link: https://oj.leetcode.com/problems/swap-nodes-in-pairs/

Question: Given a linked list, exchange two adjacent nodes and return.

Your algorithm can only use constant space. The values in the table cannot be modified, but only the nodes themselves can be changed.

Idea: first, directly switch the two nodesValue. Yes, but it does not.

public ListNode swapPairs(ListNode head) {if (head == null || head.next == null)return head;ListNode back = head;while (back != null) {if (back.next != null) {int val = back.val;back.val = back.next.val;back.next.val = val;back = back.next.next;} elsebreak;}return head;}


2nd Methods: first set a virtual header node to avoid being empty. Then swap the reference of the node.
public ListNode swapPairs(ListNode head) {ListNode dummy = new ListNode(-1);dummy.next = head;ListNode pre = dummy;while (head != null && head.next != null) {ListNode tmp = head.next.next;pre.next = head.next;head.next.next = head;head.next = tmp;pre = head;head = tmp;}return dummy.next;}



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.