LeetCode代码记录 24 Swap Nodes in Pairs

来源:互联网 发布:戈尔巴乔夫 知乎 编辑:程序博客网 时间:2024/06/11 09:59

题目如下:

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.

这道题主要还是链表的互换,比较简单,答案运行官方Case时间为4ms,仍有很多提升空间。

/** * 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* nextPointer = head;        ListNode* pPre = NULL;        ListNode* pSwap = NULL;        while(nextPointer!=NULL && nextPointer->next!=NULL) {            if( nextPointer == head) {                pSwap = nextPointer->next;                nextPointer->next = pSwap->next;                head = pSwap;                pSwap->next = nextPointer;            } else {                pSwap = nextPointer->next;                nextPointer->next = pSwap->next;                pPre->next = pSwap;                pSwap->next = nextPointer;            }            pPre = nextPointer;            nextPointer = nextPointer->next;        }        return head;    }};


0 0
原创粉丝点击