16_反转链表
来源:互联网 发布:最新网络术语 编辑:程序博客网 时间:2024/05/19 02:17
题目:输入一个链表的头结点,反转该链表并输出反转后链表的头结点。
import java.util.Scanner;class ListNode{ int value; ListNode next;}public class Main{ //递归反转 private static ListNode reverse1(ListNode head) { if(head == null || head.next == null) return head; ListNode nextNode = head.next; head.next = null; ListNode reverseRest = reverse1(nextNode); nextNode.next = head; return reverseRest; } //遍历反转 private static ListNode reverse2(ListNode cur) { if(cur == null || cur.next == null) return cur; ListNode pre = null;// 上一结点 ListNode nextNode = null;// 下一结点 // 当前结点为null,说明位于尾结点 while(cur != null){ nextNode = cur.next; cur.next = pre;// 反转指针域的指向 // 指针往下移动 pre = cur; cur = nextNode; } return pre; } private static void printReverseList(ListNode head){ ListNode tempNode = head; while(tempNode != null){ System.out.print(tempNode.value +" "); tempNode = tempNode.next; } } public static void main(String[] args) { System.out.print("请输入单链表的节点数:"); Scanner in = new Scanner(System.in); while (in.hasNext()) { ListNode node = new ListNode(); ListNode node1 = node;//用于输出原链表 ListNode node2 = node;//用于输出递归反转后的链表 ListNode node3 = node;//用于输出遍历反转后的链表 node.next = null; int N = in.nextInt();//链表结点个数 if(N <= 0) return; System.out.print("请输入链表(以空格隔开):"); for (int i = 0; i < N; i++) { ListNode p = new ListNode(); p.value = in.nextInt(); p.next = null; node.next = p; node = node.next; } System.out.print("原链表:"); printReverseList(node1.next); System.out.println(); System.out.print("递归输出:"); printReverseList(reverse1(node2.next)); System.out.println(); //System.out.print("遍历输出:"); //printReverseList(reverse2(node3.next)); } in.close(); }}
阅读全文
0 0
- 16_反转链表
- 1025_反转链表 (25)
- 剑指offer_面试题16_反转链表(两种方法)
- 16:反转链表
- 16 反转链表
- 16-反转链表
- 九度_题目1518:反转链表
- 数据结构和算法_数组/链表反转
- 题目16:反转链表
- 面试16: 反转链表
- 试题16:反转链表
- 16反转链表python
- 剑16-反转链表
- (数据结构)线性表_单链表反转 _模仿
- 左程云_算法与数据结构 — 链表问题 — 05反转部分单链表
- 栈_数列反转
- 面试题16:反转链表
- 面试题16 反转链表
- 将图片保存为h5py文件
- python 条件判断
- C语言文件读写练习:从键盘读入若干字符,并逐个将这些字符写入文件中,直至输入"#"结束。再将这些字符从文件中读出并显示到屏幕上。
- html web页面锚点的设置
- B
- 16_反转链表
- 盗链和反盗链
- Machine learning for OpenCV 学习笔记 day5
- 【转】mac终端光标快捷操作
- OPENGL学习笔记之四
- Android.mk语法简介
- Python3 正则表达式
- Glog日志模块
- Linux必学命令-文件处理类命令