题目:
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.
思路:
利用插入的办法,交换两个节点。维护一个pre节点,表示插入的前一个节点。维护一个cur节点,表示要插入的节点。同时构造一个虚拟头结点dummyhead,维护链表的头结点。
Attention:
1. 如果链表为空,或者只有一个节点,返回链表。
if(head == NULL || head->next == NULL) return head;
2. 维护三个节点。
ListNode* dummyhead = new ListNode(0); dummyhead->next = head; ListNode* cur = head; ListNode* pre = dummyhead;
3. 注意判断当cur本身指向最后一个节点时,也不进行处理。
while(cur != NULL && cur->next != NULL)
复杂度:O(N)
AC Code:
/** * 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* dummyhead = new ListNode(0); dummyhead->next = head; ListNode* cur = head; ListNode* pre = dummyhead; if(head == NULL || head->next == NULL) return head; while(cur != NULL && cur->next != NULL) { cur = cur->next; ListNode* tmp = cur->next; //保存插入节点的后一个结点 cur->next = pre->next; //将cur节点插入 pre->next = cur; pre = cur->next; //移动pre到下一个插入位置 cur->next->next = tmp; //连接交换后的节点和插入节点的后一个节点 cur = tmp; //移动cur节点 } return dummyhead->next; } };
时间: 2024-12-24 12:19:48