Swap Nodes in PairsTotal accepted:45110 Total submissions:138992my submissions QuestionSolution
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.
Hide TagsLinked ListHas you met this question in a real interview? Yes No
Discuss
This problem is not much to say, mainly the linear table of the chain storage structure, it should be noted that in the linear table of the topic, head node is the first node.
#include <iostream>using namespace std;struct listnode {int val; ListNode *next; ListNode (int x): Val (x), Next (NULL) {}}; listnode* Swappairs (listnode* head) {listnode* ptr=head; listnode* ptr0; listnode* ptr1; listnode* ptr2; listnode* temp;if (Head==null) return ptr;if (ptr->next==null) return ptr;ptr0=ptr;ptr1=ptr0->next;ptr0-> Next=ptr1->next;ptr1->next=ptr0;temp=ptr0;ptr0=ptr1;ptr1=temp;ptr=ptr0;ptr2=ptr1->next;if (Ptr2==NULL) Return Ptr;ptr2=ptr2->next;if (Ptr2==null) return Ptr;ptr1=ptr1->next;ptr0=ptr0->next;while (1) {ptr1-> Next=ptr2->next;ptr2->next=ptr1;ptr0->next=ptr2;temp=ptr1;ptr1=ptr2;ptr2=temp;if (Ptr2->next==NULL) Return Ptr;ptr2=ptr2->next;ptr1=ptr1->next;ptr0=ptr0->next;if (ptr2->next==null) return ptr;ptr2=ptr2- >next;ptr1=ptr1->next;ptr0=ptr0->next;} return ptr;}
If the head node of the linear table stored in the topic has no data stored, it is another way.
listnode* Swappairs (listnode* head) {listnode* ptr; listnode* ptr0; listnode* ptr1; listnode* ptr2; listnode* temp;ptr=ptr0=head;if (Ptr==null) return ptr;if (Ptr->next==null) return ptr;ptr1=ptr0->next;if (ptr1- >next==null) return Ptr;ptr2=ptr1->next;while (1) {ptr1->next=ptr2->next;ptr2->next=ptr1;ptr0-> Next=ptr2;temp=ptr1;ptr1=ptr2;ptr2=temp;if (ptr2->next==null) return Ptr;ptr2=ptr2->next;ptr1=ptr1->next ;p tr0=ptr0->next;if (ptr2->next==null) return ptr;ptr2=ptr2->next;ptr1=ptr1->next;ptr0=ptr0->next;} return ptr;}
int main () {listnode* head;head= (listnode*) malloc (sizeof (ListNode));head->val=1; listnode* ptr2;ptr2= (listnode*) malloc (sizeof (ListNode));head->next=ptr2;ptr2->next=null;ptr2->val=2; cout<
Leetcode_1 problem--swap Nodes in Pairs (Chain storage for linear tables)