单向链表的反转

单向链表反转一般有两种实现思路:

  • 循环遍历
  • 递归

代码如下:

package constxiong.interview;import constxiong.interview.SingleLinkedList.Node;/*** 反转单向列表* * @author ConstXiong* @date 2019-11-06 11:04:12*/
public class TestReserveLinkedList {public static void main(String[] args) {SingleLinkedList ll = new SingleLinkedList();ll.add(1);ll.add(2);ll.add(3);ll.add(4);ll.add(5);ll.print();reverseLinkedList(ll);System.out.println();ll.print();}public static void reverseLinkedList(SingleLinkedList ll) {Node first = ll.first;reverseNode(first);
//		reverseNodeByRecursion(first);ll.first = ll.last;ll.last = first;}/*** 循环逆转节点指针* @param first*/public static void reverseNode(Node first) {Node pre = null;Node next = null;while (first != null) {next = first.next;first.next = pre;pre = first;first = next;}}/*** 递归逆转节点指针* @param head* @return*/public static Node reverseNodeByRecursion(Node first) {if (first == null || first.next == null) {return first;}Node prev = reverseNodeByRecursion(first.next);first.next.next = first;first.next = null;return prev;}
}

 


【Java面试题与答案】整理推荐

  • 基础与语法
  • 集合
  • 网络编程
  • 并发编程
  • Web
  • 安全
  • 设计模式
  • 框架
  • 算法与数据结构
  • 异常
  • 文件解析与生成
  • Linux
  • MySQL
  • Oracle
  • Redis
  • Dubbo

 


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部