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


Set the head node for easy operation and reverse each two

1/** 2 * definition for singly-linked list. 3 * struct listnode {4 * int val; 5 * listnode * Next; 6 * listnode (int x): Val (x), next (null) {} 7 *}; 8 */9 class solution {10 public: 11 listnode * swappairs (listnode * head) {12 if (! Head) return head; 13 listnode node (-1); // set the header node 14 node. next = head; 15 listnode * pre = & node; 16 listnode * P = head; 17 while (P & P-> next) {// if the current node and the next node have 18 pre-> next = p-> next; 19 P-> next = p-> next; 20 pre-> next = P; 21 pre = P; 22 p = p-> next; 23} 24 return node. next; 25} 26 };


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.