主函数与新建链表、输出链表
public class Lc206 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//获取链表的节点个数
int n = Integer.parseInt(sc.nextLine());
//读取链表元素
String[] nums = sc.nextLine().split(" ");
int[] arr = new int[n];
for(int i = 0;i<n;i++){
arr[i] = Integer.parseInt(nums[i]);
}
//构建链表
ListNode head = createLinkedList(arr);
//反转链表
Solution solution = new Solution();
ListNode newHead = solution.reverseList(head);
//输出结果
printLinkList(newHead);
sc.close();
}
//创建链表
private static ListNode createLinkedList(int[] arr){
if(arr.length == 0)return null;
ListNode head = new ListNode(arr[0]);
ListNode cur = head; //保留头结点 用cur来代替创建后续链表
for(int i = 1;i<arr.length;i++){
cur.next = new ListNode(arr[i]);
cur = cur.next;
}
return head;
}
//打印链表
private static void printLinkList(ListNode head){
if(head==null){
System.out.println("null");
return ;
}
//转化为字符串进行输出
StringBuilder sb = new StringBuilder();
//遍历链表进行转换
ListNode cur = head;
while (cur!=null) {
sb.append(cur.val);
if(cur.next!=null)sb.append(" ");
cur = cur.next;
}
System.out.println(sb.toString());
}
}
//新建节点类 :属性和新建的方法
class ListNode{
int val;
ListNode next;
ListNode(int val){
this.val = val;
}
}
核心代码
class Solution{
public ListNode reverseList(ListNode head){
if(head==null||head.next==null)return head;
return reverse(null, head);
}
//递归-尾插法
public ListNode reverse(ListNode pre,ListNode cur){
if(cur == null)return pre;
//进行递归
ListNode res = reverse(cur, cur.next);
//反向
cur.next = pre;
return res;
}
//迭代-头插法
public ListNode reverse2(ListNode head){
ListNode pre = null;
ListNode cur = head;
while(cur!=null){//遍历每一个插到前面去
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}
输入处理
ACM模式下需要手动处理输入输出。通过Scanner读取用户输入,第一行为链表节点个数n,第二行为用空格分隔的链表元素值。将字符串转换为整型数组后用于构建链表。
链表构建
createLinkedList方法将整型数组转换为链表结构。初始化头节点后,通过循环依次创建后续节点,并将它们链接起来。确保链表顺序与输入顺序一致。
反转链表实现
递归法和迭代法均可实现链表反转。递归法通过不断调用自身调整指针方向,迭代法则使用循环逐个节点反转。两种方法均能正确处理空链表或单节点链表的情况。
结果输出
printLinkList方法将反转后的链表转换为字符串输出。遍历链表节点,用空格分隔各节点值,确保格式符合题目要求。若链表为空,直接输出"null"。
代码结构
ListNode类定义链表节点结构,包含val和next属性。Solution类提供两种反转方法:递归法reverse和迭代法reverse2,用户可根据需求选择。主程序逻辑清晰,各模块分工明确。


374

被折叠的 条评论
为什么被折叠?



