<span style= "font-family:arial, Helvetica, Sans-serif; Background-color:rgb (255, 255, 255); " > Topic link:https://leetcode.com/problems/swap-nodes-in-pairs</span>
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.
/** * Definition for singly-linked list. * struct ListNode {* int val; * struct ListNode *next; *}; */struct listnode* swappairs (struct listnode* head) { struct ListNode *prenode, *firstnode, *secondnode; if (head = = NULL | | head->next = = NULL) return head; Firstnode = head; Secondnode = head->next; head = Secondnode; Firstnode->next = secondnode->next; Head->next = Firstnode; Prenode = Firstnode; while (Prenode->next = null && prenode->next->next! = null) { Firstnode = prenode->next; Secondnode = firstnode->next; Prenode->next = Secondnode; Firstnode->next = secondnode->next; Secondnode->next = Firstnode; Prenode = Firstnode; } return head;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
#24 Swap Nodes in Pairs