zoukankan      html  css  js  c++  java
  • 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;
        }
    }
    
  • 相关阅读:
    Matlab 画图
    OfferCome-0531
    OfferCome--0528
    剑指offer(2)
    剑指offer(1)
    MySQL的自增主键
    java Junit 测试
    sql 注入问题
    Facebook Libra
    markdown的博客
  • 原文地址:https://www.cnblogs.com/masterlibin/p/5824156.html
Copyright © 2011-2022 走看看