分组反转链表

题目原型:

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

You may not alter the values in the nodes, only nodes itself may be changed.

Only constant memory is allowed.

For example,
Given this linked list: 1->2->3->4->5

For k = 2, you should return: 2->1->4->3->5

For k = 3, you should return: 3->2->1->4->5

分析:

这个题目是意思就是说把这个链表按K值分组翻转,即以k为单位,如果不足k者不变化。例如k=2时,链表1->2->3->4->5,按1->2,3->4,5 分组,反转后变为2->1->4->3->5

//翻转链表
	public ListNode reverse(ListNode head)
	{
		if(head==null)
			return null;
		ListNode p,q,t=null;
		p = head;
		q = p.next;
		if(q!=null)
			t = q.next;
		//把头结点设置成尾节点
		head.next = null;
		while(q!=null)
		{
			q.next = p;
			p = q;
			q = t;
			if(t!=null)
				t = t.next;
		}
		return p;
	}
	public ListNode reverseKGroup(ListNode head, int k) 
	{
		if(head==null)
			return null;
		
		ListNode p;
		ListNode firstNode,nextfirstNode;//反转后的子链表的头指针和下一段链表的头指针,供反转后连接母链表时使用
		ListNode headNode = head;//待翻转的子链表的头指针
		ListNode preTail = null;//指向上一段链表的尾节点
		p = head;
		
		int count = 0;
		
		while(p!=null)
		{
			if(count==0)
				headNode = p;
			count++;
			if(count==k)
			{
				count=0;
				nextfirstNode = p.next;
				p.next = null;
				firstNode = reverse(headNode);
				headNode.next = nextfirstNode;//连接上母链表,现在headNode指向的是尾节点
				if(preTail!=null)
					preTail.next = firstNode;
				if(preTail==null)
					head = firstNode;
				preTail = headNode;//指向本次被翻转的链表的尾节点,作为下一次的上一段链表的尾节点
				p = preTail.next;
				continue;
			}
			p = p.next;
		}
		return head;
    }


分组反转链表

上一篇:sql查询结果横向显示


下一篇:win7(32/64)+php5.5+apache2.4+mysql5.6 搭建