定义一个结点类:
class Node {
int val;
Node next;
public Node(int val) {
this.val = val;
}
}
图解:【这里以头删+头插为例】
翻转链表:
package com.basic.datastructure;
//翻转链表
public class ReverseListNode {
//1.头插+头删
public static Node reverseListNode(Node head){
if(head==null || head.next==null) return head;
Node cur=head;
Node newNode=null;
while(cur!=null){
Node node=cur.next;
cur.next=newNode;
newNode=cur;
cur=node;
}
return newNode;
}
//2.就地反转
public static Node reverseList(Node head){
if(head==null || head.next==null){
return head;
}
Node cur=head;
Node prev=null;
while(cur!=null){
Node node=cur.next;
cur.next=prev;
prev=cur;
cur=node;
}
return prev;
}
//打印链表结点
public static void printListNode(Node head){
Node cur=head;
while(cur!=null){
System.out.print(cur.val+",");
cur=cur.next;
}
}
public static void main(String[] args) {
Node node1=new Node(1);
Node node2=new Node(2);
Node node3=new Node(3);
Node node4=new Node(4);
Node node5=new Node(5);
node1.next=node2;
node2.next=node3;
node3.next=node4;
node4.next=node5;
printListNode(node1);
System.out.println();
//Node rst=reverseListNode(node1);
Node rst=reverseList(node1);
printListNode(rst);
}
}
运行结果: