Problem:
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.
所以这题的做法就是一系列的链表结点的交换。
我的做法时间复杂度O(n),空间复杂度O(1)。
Code:(LeetCode运行3ms)
/**
* 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) {
if (head == NULL || head -> next == NULL) {
return head;
}
ListNode *newhead = new ListNode(-1);
newhead -> next = head;
ListNode *prev = newhead, *position = head;
while (position != NULL && position -> next != NULL) {
prev -> next = position -> next;
prev = prev -> next;
position -> next = prev -> next;
prev -> next = position;
position = position -> next;
prev = prev -> next;
}
return newhead -> next;
}
};