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