Fork me on GitHub

24. Swap Nodes in Pairs

24. Swap Nodes in Pairs

题目

 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. 

解析


class Solution_24 {
public:
	/*两个指针分别指向奇数和偶数位置,一个指针指向前一次的结尾处先调换位置,再将其挂到上一次结尾处之后继续调整三个指针位置即可
	*/
	ListNode* swapPairs(ListNode* head) {
		if (head == NULL || head->next == NULL)
		{
			return head;
		}
		ListNode* newHead = NULL;
		ListNode* pre = NULL, *cur = head;
		ListNode* next = NULL;
		ListNode* temp=NULL;
		while (cur&&cur->next)
		{
			pre = cur;
			cur = cur->next;
			next = cur->next;

			pre->next = next;
			cur->next = pre;
			if (temp)
			{
				temp->next = cur; //当前挂载上一次的结尾指针上
			}	
			if (!newHead)
			{
				newHead = cur;
			}
			temp = pre; ///记录上一次的结尾指针
			cur = next;
		}

		return newHead;
	}
};

主要的思想是递归,拆分成2部分:

1,将第3个节点开始的链表作为下一次递归的参数,用它去继续交换。
2,将第1个节点指向递归返回的结果,将第2个节点重新指向第1个节点,并返回它,这是新的head。

递归终止的两种情况:

1,没有节点了,返回NULL作为结束。
2,只有一个节点了,不用交换,直接返回它即可。

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if(head == NULL) return NULL;
        if(head->next == NULL) return head;

        ListNode* temp = head->next;
        head->next = swapPairs(temp->next);
        temp->next = head;

        return temp;
    }
};

题目来源

posted @ 2018-01-23 20:01  ranjiewen  阅读(285)  评论(0编辑  收藏  举报