您的位置:首页 > 理论基础 > 数据结构算法

单向链表反转

2016-10-30 22:48 281 查看
记录几种单项链表反转的实现,代码仅java实现。

链表结点结构定义为:

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  链表 数据结构