链表翻转

给出一个链表和一个数k,比如链表1→2→3→4→5→6,k=2,则翻转后2→1→4→3→6→5,若k=3,翻转后3→2→1→6→5→4,若k=4,翻转后4→3→2→1→5→6

struct Node
{
	int value;
	Node *next;
};

Node* reverseList(Node *head, int k)
{
    if (NULL == head || k < 1) 
	{
		return NULL;
	}
	if (k == 1)
	{
		return head;
	}

	Node *newHead = NULL;
	Node *prev = NULL;
	Node *begin = head;
	Node *end = head;
	Node *p = NULL;
	Node *q = NULL;
	bool firstHandled = false;
	while (begin)
	{
		int count = k-1;
		end = begin;
		while (count && end->next != NULL)
		{
			end = end->next;
			count--;
		}
		if (count != 0)
		{
			if (newHead == NULL)
			{
				newHead = begin;
			}
			else
			{
				prev->next = begin;
			}
			return newHead;
		}
		p = begin->next;
		q = begin;
        while (q != end)
		{
			Node *temp = p->next;
			p->next = q;
			q = p;
			p = temp;
		}
		if (prev == NULL)
		{
			newHead = end;
		}
		else
		{
			prev->next = end;
		}
		prev = begin;
		prev->next = NULL;

		begin = p;
	}

	return newHead;
}


你可能感兴趣的:(链表翻转)