目录
1 翻转单链表
递归和非递归代码如下:
package org.example;
class Node<T> {
T val;
Node next;
public Node(T val) {
this.val = val;
}
public Node(T val, Node next) {
this.val = val;
this.next = next;
}
}
public class ReverseList {
/**
* while方式反转
*/
public static Node reverse(Node head) {
if (head == null || head.next == null) {
return head;
}
Node reHead = null;
while (head != null) {
Node cur = head.next;//定义临时变量cur:下一个节点的值
head.next = reHead;
reHead = head;
head = cur;
}
return reHead;
}
/**
* 递归方式反转
*/
public static Node reverseWithRecursion(Node head) {
if (head == null || head.next == null)
return head;
Node newNode = reverseWithRecursion(head.next);
head.next.next = head;//
head.next = null;
return newNode;
}
public static void printList(Node head) {
if (head == null) {
return ;
}
while (head != null) {
System.out.print(head.val + "-->");
head = head.next;
}
}
public static void main(String[] args) {
Node a5 = new Node(5);
Node a4 = new Node(4,a5);
Node a3 = new Node(3,a4);
Node a2 = new Node(2,a3);
Node a1 = new Node(1,a2);
// 方式1
Node rehead = reverse(a1);
// 方式2
// Node rehead = reverseWithRecursion(n1);
printList(rehead);
}
}
2 链表翻转相邻节点
递归:
public static Node swapPairs(Node head) {
if(head == null||head.next == null){
return head;
}
Node first = head;
Node second = head.next;
first.next = swapPairs(second.next);
second.next = first;
//转载请标明链接:https://blog.csdn.net/wabiaozia/article/details/106729417
return second;
}
迭代:
public static Node swapPairs2(Node head) {
Node dummy = new Node(-1);
dummy.next = head;
Node prev = dummy;
while (head != null && head.next != null){
Node first = head;
Node second = head.next;
prev.next = second;
first.next = second.next;
second.next = first;
prev = first;
head = first.next;
}
return dummy.next;
}
//注释版
//转载请标明链接:https://blog.csdn.net/wabiaozia/article/details/106729417
public static Node swapPairs2(Node head) {
Node dummy = new Node(-1);
dummy.next = head;
Node prev = dummy;
while (head != null && head.next != null){
Node first = head;
Node second = head.next;
//以第一次翻转举例,传入1节点,prev=null
prev.next = second;//prev指向2 null->2
first.next = second.next;//1的下一个节点指向2的下一个节点,即1的下一个节点指向3
second.next = first;//12节点指向互换,即2的下一个节点指向1,这三步后null->2->1->3->4->5->6
prev = first;//重置prev节点,为下一次翻转做准备
head = first.next;//重置head节点,为下一次翻转做准备
}
return dummy.next;
}
3 链表每K个节点翻转
遍历K个节点,调用翻转链表,再和原有的节点拼接头尾
转载请标明链接:https://blog.csdn.net/wabiaozia/article/details/106729417