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.

这个问题我们先建一个头结点,这样可以统一操作,每一步就那么几个操作,见图。

Swap Nodes in Pairs_第1张图片

这样就不用特别处理第一结点,好了看明白这个图说的步骤就代码。

class Solution {
public:
	ListNode *swapPairs(ListNode *head) {
		if(head == NULL || head->next == NULL)
			return head;
		ListNode *pre, *tail;
		ListNode *new_head = new ListNode(-1);
		new_head->next = head;
		pre = new_head;
		while(pre->next && pre->next->next)
		{
			tail = pre->next->next;
			pre->next->next = tail->next;
			tail->next = pre->next;
			pre->next = tail;
			pre = tail->next;
		}
		pre = new_head;
		new_head = new_head->next;
		delete pre;
		return new_head;
	}
};

leetcode里有好多链表题,这里是创建链表的函数,想自己测试的在这里下: 创建链表函数

你可能感兴趣的:(LeetCode,Algorithm,C++,list,Class,linked)