[LeetCode] Swap Nodes in Pairs

来源:互联网 发布:windows清理助手怎么样 编辑:程序博客网 时间:2024/06/15 18:08

题目:

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.

题解:

算法很直观,直接一次遍历就行了,要多注意下指针的移动,为了方便处理,定义了一个头指针

代码如下:


/** * 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 *h= (ListNode *)malloc(sizeof(ListNode));h->next = head;if (head == NULL || head->next == NULL){return head;}ListNode *pre = h;ListNode *ptr = pre->next;ListNode *tail = ptr->next;while ( true ){pre->next = tail;ptr->next = tail->next;tail->next = ptr;pre = ptr;if (ptr->next)ptr = ptr->next;elsebreak;if (ptr->next)tail = ptr->next;elsebreak;}return h->next;}};


0 0
原创粉丝点击