Swap Nodes in Pairs

brucehb發表於2017-02-14

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.

struct Node
{
	int val;
	Node *next;
	Node(int x) : val(x), next(NULL){}
};

Node* fun(Node *head)
{
	if (head == NULL)
	{
		return NULL;
	}

	Node *result = head;
	Node *p = head;
	Node *q = p->next;
	Node *prev = NULL;
	while (p != NULL && q != NULL)
	{
		Node *temp = q->next;
		if (result == head)
		{
			result = q;
		}
		else
		{
			prev->next = q;
		}
		q->next = p;
		p->next = temp;
		prev = p;
		
		p = temp;
		if (p != NULL)
		{
			q = p->next;
		}
	}

	return result;
}


相關文章