1. 程式人生 > >算法總結之 反轉部分單向鏈表

算法總結之 反轉部分單向鏈表

import class pos node span art cnblogs ++ !=

給定單鏈表的表頭節點head, 以及兩個整數from 和 to, 在單向鏈表上把fro個節點到第to個節點這一部分進行反轉

思路:

本題 有可能存在換頭的問題,所以函數應該返回調整後的新的頭節點

1 判斷是否滿足 1<=from<=to<=N 如果不滿足,直接返回原來的頭節點

2 找到第from-1個節點pre和第to+1個節點tPos,fPre即要反轉部分的前一個節點,tPos是反轉部分的後一個節點,把反轉部分先反轉,然後正確的鏈接fPre和tPos

package TT;

import TT.Test85.Node;

public class Test90 {

    
public Node reversePart(Node head, int from , int to){ int len = 0; Node node1=head; Node fPre = null; Node tPos = nullwhile(node1!= null){ len++; fPre = len == from-1 ? node1 : fPre; tPos = len== to+1 ? node1 : tPos; node1
=node1.next; } if(from<to || from<1 || to>len){ return head; } node1 = fPre==null ? head:fPre.next; Node node2 = node1.next; node1.next = tPos; Node next = null; while(node2 !=tPos){ next = node2.next; node2.next
= node1; node1 = node2; node2 = next; } if(fPre != null){ fPre.next=node1; return head; } return node1; } }

算法總結之 反轉部分單向鏈表