- 链表之反转链表,一招鲜吃遍天(java求解)
- 解题万金油
- 栗子1:反转整个链表
- 栗子2:反转某个区间内的链表
- 栗子3:按照k为一组,反转某个区间内的链表
链表的反转一类的算法题,在面试中经常被问,题目的花样也很多,整体反转、部分反转、分组反转等等。这类题的解法也是有很多种,递归、指针等等。
对于这种题,最核心的地方就是反转的逻辑怎么处理,其他的比如整体、部分这些,通过循环就可以解决。
解题万金油反转的逻辑怎么写?很简单,记得一个就可以:
- 实例化一个空节点newHead,指向head
- 实例一个cur,作为newHead的下一个节点
- 实例一个cur_next,作为cur的next
- 另cur.next = cur_next.next
- cur_next.next = newHead.next
- newHead.next = cur_next
按照这几个步骤,做几个小栗子
栗子1:反转整个链表描述:给定一个链表,翻转链表,并返回新的头节点head
输入:[1,2,3,4] 输出:[4,3,2,1] 返回:head=4
按照步骤:
-
// 实例一个空节点,指向head ListNode newHead = new ListNode(-1); newHead.next = head;
-
// 实例一个cur,作为newHead的下一个节点 ListNode cur = newHead.next;
-
// 实例一个cur_next,作为cur的next ListNode cur_next; cur_next = cur.next;
-
// 另cur.next = cur_next.next cur.next = cur_cur_next.next; // cur_next.next = newHead.next cur_next.next = newHead.next; // newHead.next = cur_next newHead.next = cur_next;
补充上我们要在哪些地方进行翻转,也就是空值循环范围,完整代码
public ListNode ReverseList(ListNode head) {
ListNode myNode = new ListNode(-1);
myNode.next = head;
ListNode ptr = myNode;
ListNode cur = ptr.next;
ListNode cur_next;
while(cur != null && cur.next != null){
cur_next = cur.next;
cur.next = cur_next.next;
cur_next.next = ptr.next;
ptr.next = cur_next;
}
return myNode.next;
}
栗子2:反转某个区间内的链表
描述:给定一个链表,和一个区间,只翻转链表的这个区间内的数据
输入:[1,2,3,4,5] (2,4) 输出:[1,4,3,2,5] 返回:head:1
按照步骤,翻转部分都是不变的,只是我们把指针移到要翻转的地方就可以
public ListNode reverseBetween (ListNode head, int m, int n) {
// write code here
ListNode myNode = new ListNode(-1);
myNode.next = head;
ListNode ptr = myNode;
// 前面的不需要变动
for(int i = 0; i < m-1; i++){
ptr = ptr.next;
}
// 从这里开始翻转
ListNode cur = ptr.next;
ListNode cur_next;
for(int i = 0; i < n - m; i++){
cur_next = cur.next;
cur.next = cur_next.next;
cur_next.next = ptr.next;
ptr.next = cur_next;
}
// 后面的不用动,直接返回
return myNode.next;
}
栗子3:按照k为一组,反转某个区间内的链表
描述:给定一个链表,和一个区间,只翻转链表的这个区间内的数据
输入:[1,2,3,4,5] (3) 输出:[3,2,1,4,5] 返回:head:3
可以按照k进行分组,两层循环对每个组内的链表进行翻转
public ListNode reverseKGroup (ListNode head, int k) {
// write code here
// 如果链表为空返回null
if (head == null) return null;
if (k == 1) return head;
// 链表长度
int len = getLength(head);
// 按照k进行分组,该链表可以分为num组,个数不到k的不处理
int num = len / k;
// 定义一个node,指向第一个节点
ListNode newNode = new ListNode(-1);
newNode.next = head;
ListNode ptr = newNode;
ListNode cur_next;
ListNode cur;
// 按照分组遍历
for(int i = 0; i < num; i++){
cur = ptr.next;
// 对每一组的数据处理
for(int j = 0; j < k-1; j++){
cur_next = cur.next;
cur.next = cur_next.next;
cur_next.next = ptr.next;
ptr.next = cur_next;
}
ptr = cur;
}
return newNode.next;
}
// 获取链表长度
public int getLength(ListNode head){
int i = 0;
while (head != null){
head = head.next;
i += 1;
}
return i;
}
这类题的关键就是对于不同范围的翻转链表,我们应该怎么处理newHead节点在哪,也就是翻转从哪里开始到哪里结束的问题。多刷一些这个类型的题,问题就迎刃而解了。



