Total Accepted: 73777 Total Submissions: 219963 Difficulty: Medium
Given a linked list, swap every two 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. You may not modify the values in the list, only nodes itself can be changed.
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* swapPairs(ListNode* head) { ListNode* first=head; ListNode* second = first ? first->next:NULL; ListNode* next=NULL,*pre=NULL; while(first && second){ next = second->next; second->next = first; first->next = next; pre ? pre->next = second: head = second;//有前驱的话,前驱的下一几点指向交换后的两个节点的头,否则,为第一次交换,更新头结点. pre = first; first=next; second = first ? first->next:NULL; } return head; } };
Next challenges: (H) Reverse Nodes in k-Group