ReverseLinkedList,ReverseLinkedList2,链表反转问题

Posted 32ddd

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ReverseLinkedList,ReverseLinkedList2,链表反转问题相关的知识,希望对你有一定的参考价值。

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,链表反转问题的主要内容,如果未能解决你的问题,请参考以下文章

206. Reverse Linked Listeasy

[leetcode] Reverse Linked List

206. Reverse Linked List

[LeetCode]Reverse Linked List

[LeetCode] 206. Reverse Linked List ☆(反转链表)

LeetCode Reverse Linked List