Java算法(6):反转单链表

1.遍历实现 通用实现方法,速度最快

/**
* 遍历实现 通用实现方法
*
* @param head
* @return
*/
public static DataNode reverse2(DataNode head) {
if (null == head || null == head.getNext())
return head;
DataNode pre = head;
DataNode cur = head.getNext();
while (null != cur.getNext()) {
DataNode tmp = cur.getNext();
cur.setNext(pre);
pre = cur;
cur = tmp;
}
cur.setNext(pre);
head.setNext(null);
return cur;
}

2.递归实现,速度较慢,当栈深度大于12000 则会出现StakOverflowError

/**
* 递归实现 当栈深度大于12000 则会出现StakOverflowError
*
* @param head
* @return
*/
public static DataNode reverse1(DataNode head) {
if (null == head || null == head.getNext())
return head;
DataNode revHead = reverse1(head.getNext());
head.getNext().setNext(head);
head.setNext(null);
return revHead;
}

3.借助stack实现,速度很慢

/**
* 方法3 利用其他数据结构 stack
* @param head
* @return
*/
public static DataNode reverse3(DataNode head) {
Stack<DataNode> stack = new Stack<DataNode>();
for (DataNode node = head; null != node; node = node.getNext()) {
stack.add(node);
}
DataNode reHead = stack.pop();
DataNode cur = reHead;
while(!stack.isEmpty()){
cur.setNext(stack.pop());
cur = cur.getNext();
cur.setNext(null);
}
return reHead;
}

推荐阅读更多精彩内容