[Leetcode] swap nodes in pairs

Source: Internet
Author: User

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 mayNotModify the values in the list, only nodes itself can be changed.

Resolution: Based on an ordered linked list, swap two adjacent nodes and return the linked list header. Only constant space can be used, and the value inside the node cannot be changed. The main idea is to define two record pointers P1 and P2. P1 indicates the nodes to be processed that are currently traversed in the linked list. P2 indicates the last node in the linked list that has been successfully exchanged.

Note two points: (1) because the linked list may have an even number of nodes or an odd number of nodes, pay special attention to the situation when there are odd numbers of nodes.

(2) Pay attention to the steps before and after the links between the linked list and the deleted links, which are prone to errors.

Java AC code:

Public class solution {public listnode swappairs (listnode head) {If (Head = NULL | head. next = NULL) {return head;} listnode dummy = new listnode (-1); dummy. next = head; listnode p1 = head; listnode P2 = dummy; while (P1! = NULL & p1.next! = NULL) {p2.next = p1.next; p1.next = p1.next. next; p2.next. next = p1; P2 = p2.next. next; P1 = p1.next; If (p1 = NULL) {return dummy. next;} else if (p1.next = NULL) {p2.next = p1; return dummy. next;} return dummy. next ;}}



[Leetcode] swap nodes in pairs

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.