单向链表反转
2016-10-30 22:48
281 查看
记录几种单项链表反转的实现,代码仅java实现。
链表结点结构定义为:
输入示例:2 3 4 5 #
链表结点结构定义为:
public class Node { int val; Node next; public Node() {} public Node(int val) { this.val = val; } }
单向链表创建
终端输入字符串以 # 结束输入示例:2 3 4 5 #
public static void main(String[] args) { Scanner sc = new Scanner(System.in); Node head = null; Node parent = null; while(sc.hasNext()) { String ipt = sc.next(); if (ipt.equals("#")) break; int val = Integer.valueOf(ipt); if (parent == null) { head = new Node(val); parent = head; continue; } Node node = new Node(val); parent.next = node; parent = node; } sc.close(); }
递归
/** * @param head * @return */ private static Node reverseQueue(Node head) { if(head == null) return null; if (head.next == null) return head; Node newHead = reverseQueue(head.next); head.next.next = head; head.next = null; return newHead; }
非递归
使用栈(额外空间复杂度高)
/** * @param head * @return */ private static Node reverseQueue(Node head) { Stack<Node> nodes = new Stack<>(); while (head != null) { nodes.push(head); head = head.next; } Node pre = null; Node newHead = null; while(!nodes.isEmpty()) { if (pre == null) { newHead = nodes.pop(); pre = newHead; continue; } pre.next = nodes.peek(); pre = nodes.pop(); } // important !!! pre.next = null; return newHead; }
额外空间复杂度O(1)
/** * 非递归,额外空间O(1) * @param head * @return */ private static Node reverseQueue3(Node head) { if (head == null) return null; Node cur = head.next; Node tmp = null; // 第一个结点的后继结点要设为null if (cur != null) { tmp = cur; cur = cur.next; tmp.next = head; head.next = null; } while(cur != null) { head = tmp; tmp = cur; cur = cur.next; tmp.next = head; } return tmp; }
相关文章推荐
- 数学解题(一)单向链表反转
- 单向链表遍历反转 Javascript实现
- 单向链表反转
- 华为机试题(8)--单向链表的建立,反转(逆序),遍历显示,删除
- 链表之反转部分单向链表
- 《算法之美》の链表问题の单向链表的反转
- 单向链表反转(倒置)问题
- 链表问题——反转单向链表和双向链表
- 单向链表反转算法——递归版和迭代版
- 使用递归和非递归方式反转单向链表
- 单向链表反转
- C递归实现单向链表的反转
- C递归实现单向链表的反转
- 链表问题---反转单向和双向链表
- 反转单向和双向链表简化
- 反转单向链表
- 单向链表实现反转
- 递归方法反转单向链表(C/C++)
- 反转单向链表(reverse a singly linked list)
- 左程云_算法与数据结构 — 链表问题 — 04反转单向和双向链表