题目:
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.
交换链表相邻结点
思路:只要保存头结点,然后理清交换结点位置就好了
例如链表现在是1->2->3->4,head指向1,新建一个结点root,root->next指向head
第一次循环:pre指向root,要交换12,首先保存2的下一个结点3,接下来让pre->next为2,2的next为1,1的next为刚才保存的3,然后让head指向3,pre指向1就好了,然后继续
代码:
/** * 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 *root = new ListNode(0); root->next = head; ListNode *pre = root; while(head && head->next) { ListNode* tmp = head->next->next; pre->next = head->next; pre->next->next = head; head->next = tmp; pre = head; head = head->next; } return root->next; } };