本文共 693 字,大约阅读时间需要 2 分钟。
题目:
解答:
对链表的考察 算是比较经典的一道题目
循环取出未处理的链表的头两个节点,交换位置,链接到已处理节点的尾部。
这里要注意的是last节点,cur节点 nextcur节点的更新。
在纸上多画画,就可以清楚了。
这道题需要再做一遍,加深印象。
代码:
class Solution {public: ListNode *swapPairs(ListNode *head) { ListNode *cur = head; ListNode *nextcur; ListNode *last; if (head == NULL) return head; if (head->next == NULL) return head; cur = head; head = head->next; nextcur = head->next; head->next = cur; cur->next = nextcur; cur = nextcur; last = head->next; while (1) { if (cur == NULL) return head; if (cur->next == NULL) return head; nextcur = cur->next->next; cur->next->next = cur; last->next = cur->next; last = cur; cur->next = nextcur; cur = nextcur; } }};
转载地址:http://mutsi.baihongyu.com/