间隔K翻转链表

1->2->3->4->5->6->7 k=3 return 3->2->1->6->5->4->7

ListNode * reverse(ListNode *head,int k)
	{
		ListNode *pre = NULL;
		while (k>0)
		{
			k--;
			ListNode *next = head->next;
			head->next = pre;
			pre = head;
			head = next;
		}
		return pre;
	}
	ListNode * rservesLink(ListNode *head, int k)
	{
		ListNode *newhead = NULL;//用于存返回的头
		int count = k;
		ListNode *nexthead = head;//用于向下走
		ListNode *prehead = NULL;//存储上一个该翻转的头
		while (nexthead)
		{
			prehead = nexthead;
			while (count--)
			{
				if (nexthead==NULL)//最后没有count个
				{
					head->next = prehead;
					return newhead;
				}
				nexthead = nexthead->next;
			}
			if (newhead == NULL)
			{
				newhead = reverse(head, 3);
			}
			else
			{
				head->next = reverse(prehead, 3);
				head = prehead;
			}
			count = k;
		}
		count = k;
		head->next = reverse(head,k);
		return newhead;
	}

递归:

class Solution {
public:
	ListNode *reverse(ListNode*head, int k)
	{
		ListNode*node = head;
		ListNode*pre = NULL;
		ListNode*next = NULL;
		int count = 0;
		ListNode*nodecopy = head;
		while (nodecopy&&countnext;
		}
		if (count < k)
		{
			return head;
		}
		else
		{
			count = 0;
			while (node&&countnext;
				node->next = pre;
				pre = node;
				node = next;
				count++;
			}
		}
		if (next)
		{
			head->next = reverse(next, k);
		}
		return pre;
	}
};



你可能感兴趣的:(leetcode)