码迷,mamicode.com
首页 > 其他好文 > 详细

ReverseLinkedList,ReverseLinkedList2,链表反转问题

时间:2016-08-31 00:47:24      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:

ReverseLinkedList:

public class ReverseLinkedList 
{
	public ListNode reverseList(ListNode head) 
	{
        if(head == null || head.next == null)
        {
            return head;
        }
        ListNode pPre = new ListNode(0);
        pPre.next = head;
        ListNode curr = head;
        ListNode pNext = null;
        while(curr != null)
        {
            pNext = curr.next;
            curr.next = pPre;
            pPre = curr;
            curr = pNext;
        }
        head.next = null;
        return pPre;
    }
}

 

ReverseLinkedList2:

Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example:
Given 1->2->3->4->5->NULLm = 2 and n = 4,

return 1->4->3->2->5->NULL.

 算法分析:其实就是反转链表加了个条件,先找到第m-1个元素,m个元素,第n+1个元素,反转后再连接起来。

public class ReverseLinkedList2 
{

	public ListNode reverseBetween(ListNode head, int m, int n) 
	{
		ListNode temp1 = new ListNode(0);
		//新的头结点
		ListNode newHead = temp1;
		temp1.next = head;
		//找到第m-1个节点
        for(int i = 1; i < m; i ++)
        {
        	temp1 = temp1.next;
        }
        ListNode temp2 = new ListNode(0);
        temp2.next = head;
        //找到第n+1个节点
        for(int i = 0; i < n+1; i ++)
        {	
        	temp2 = temp2.next;
        }
        //第m个节点
        ListNode temp = temp1.next;
        //反转第m到n节点
        ListNode pPre = new ListNode(0);
        pPre.next = temp;
        ListNode pCurr = temp1.next;
        ListNode pNext = null;
        while(pCurr != temp2)
        {
        	pNext = pCurr.next;
        	pCurr.next = pPre;
        	pPre = pCurr;
        	pCurr = pNext;
        }
        temp1.next = pPre;
        temp.next = temp2;
        return newHead.next;
    }
}

 

ReverseLinkedList,ReverseLinkedList2,链表反转问题

标签:

原文地址:http://www.cnblogs.com/masterlibin/p/5824156.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!