Leetcode Swap Nodes in Pairs

Source: Internet
Author: User

1. Topics

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.


2. Solution


Class Solution {public:       listnode *swappairs (ListNode *head) {       listnode* returnnode  = head; listnode* Prenode = Null;while (head! = NULL && Head->next! = null) {listnode* firstnode = head; listnode* Secondnode = head->next;if (prenode! = NULL) {//first nodeprenode->next = Secondnode;} Else{if (Secondnode! = NULL) {returnnode = Secondnode;}} Firstnode->next = Secondnode->next;secondnode->next = Firstnode;prenode = Head;head = Head->next;} return returnnode;}    ;

idea: This question is still relatively simple. While loop, swapping two pointers. But pay attention to the details and the values returned.


http://www.waitingfy.com/archives/1583


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.