package common;
import java.util.Scanner;
/**
* @author : zhaoliang
* @program :newCoder
* @description : 翻转链表
* @create : 2020/11/21 09:53
*/
public class ReverseList {
//输入一个链表,翻转链表后输出链表的所有结点
public static class ListNode{
int val;
ListNode next;
ListNode(int x){
val = x;
}
}
public static ListNode reverseList(ListNode head){
ListNode pre = null;
ListNode next = null;
while(head!=null){
//保存翻转链表的头节点
next = head.next;
//当前要翻转的指向上一个已经翻转的结点,第一次指向null
head.next = pre;
//上一个已经翻转到头的结点
pre = head;
//一直往前走
head = next;
}
return pre;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ListNode a = new ListNode(scanner.nextInt());
ListNode b = new ListNode(scanner.nextInt());
ListNode c = new ListNode(scanner.nextInt());
ListNode d = new ListNode(scanner.nextInt());
ListNode e = new ListNode(scanner.nextInt());
a.next = b;
b.next = c;
c.next = d;
d.next = e;
reverseList(a);
while (e!=null){
System.out.println(e.val);
e = e.next;
}
}
}
常见算法-翻转链表
最新推荐文章于 2022-03-29 14:16:29 发布