题目介绍
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list’s nodes, only nodes itself may be changed.
Example:
1 | Given 1->2->3->4, you should return the list as 2->1->4->3. |
解
1 | /** |
2 | * Definition for singly-linked list. |
3 | * struct ListNode { |
4 | * int val; |
5 | * ListNode *next; |
6 | * ListNode(int x) : val(x), next(NULL) {} |
7 | * }; |
8 | */ |
9 | class Solution { |
10 | public: |
11 | ListNode* swapPairs(ListNode* head) { |
12 | ListNode first(-1); |
13 | first.next = head; |
14 | ListNode* pre = &first; |
15 | while (head != NULL && head->next != NULL) { |
16 | ListNode* node = head->next; |
17 | head->next = node->next; |
18 | node->next = head; |
19 | pre->next = node; |
20 | pre = head; |
21 | head = head->next; |
22 | } |
23 | return first.next; |
24 | } |
25 | }; |
Runtime: 4 ms
Memory Usage: 8.5 MB