数据结构专题——指定区间反转链表(java)
首先依旧是链表的定义:(leetcode方式)
class ListNode {
int val;
ListNode next;
public ListNode(int val) {
this.val = val;
next = null;
}
}
方法一(推荐):头插法:拿到反转区间的前一个结点,进行一个个头插
public static ListNode reverseByHeadInsert(ListNode list, int n, int m) {
if(list == null || list.next == null) {
return list;
}
ListNode pre = new ListNode(-1);
pre.next = list;
for (int i = 0; i < n-1; i++) {
pre = pre.next;
}
ListNode cur = pre.next;
for (int j = 0; j < m-n; j++) {
ListNode temp = cur.next;
cur.next = temp.next;
temp.next = pre.next;
pre.next = temp;
}
return list;
}
方法二:穿针引线法:将链表要反转的区间单独切割出来,再"缝合"回去
public static ListNode reverseByCut(ListNode list, int n, int m) {
if(list == null || list.next == null) {
return list;
}
ListNode pre = new ListNode(-1);
pre.next = list;
for (int i = 0; i < n-1; i++) {
pre = pre.next;
}
ListNode leftNode = pre.next;
ListNode rightNode = pre;
for (int i = 0; i < m-n+1; i++) {
rightNode = rightNode.next;
}
ListNode behind = rightNode.next;
rightNode.next = null;
ListNode newList = reverseLinkedListByRecursive(leftNode);
pre.next = newList;
leftNode.next = behind;
return list;
}
public static ListNode reverseLinkedListByRecursive(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newHead = reverseLinkedListByRecursive(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
初始化链表的方法
public static ListNode initList(int[] array) {
ListNode node = new ListNode(0);
ListNode head = node;
for(int i = 0; i < array.length; i++) {
ListNode temp = new ListNode(array[i]);
node.next = temp;
node = node.next;
}
return head.next;
}
打印链表的方法
public static String printList(ListNode head) {
if(head == null) {
return "";
}
ListNode cur = head;
StringBuilder sb = new StringBuilder();
while(cur != null) {
sb.append(cur.val).append("->");
cur = cur.next;
}
sb.append("null");
return sb.toString();
}
测试方法
public static void main(String[] args) {
int[] arr = new int[]{1,2,3,4,5,6,7,8};
ListNode list = initList(arr);
System.out.println(printList(list));
ListNode newList = null;
newList = reverseByCut(list, 2, 7);
System.out.println(printList(newList));
}
其中一个结果:
