您的位置:首页 > 其它

反转链表

2017-12-07 14:09 162 查看
题目描述:输入一个链表,反转链表后,输出链表的所有元素。

public class ListNode {
int val;
ListNode next = null;

ListNode(int val) {
this.val = val;
}
}

思路一:非递归
*head为空时,直接返回null;

*head为当前结点,pre为当前结点的前一结点,next为当前结点的下一结点。

*pre结点可以反转指向,但反转之后如果不用next结点保存next结点的话,链表就断开了

*循环:

先用next保存下一个结点的信息,保证单链表不会因为失去head结点的原next结点而就此断裂;

保存完next,可以让head从指向next变成指向pre

head指向pre后,就继续依次反转下一个结点

让pre、head、next依次向后移动一个结点,继续下一次的指针反转。

*如果head为null的时候,pre就为最后一个结点,但是链表已经反转完毕,pre就是反转后链表的第一个结点。

public class Solution {
public ListNode ReverseList(ListNode head) {
if (head == null)
return null;

ListNode pre = null;
ListNode next = null;
while (head != null)
{
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
}

思路二:递归
先反转后面的链表,走到链表的末端结点;

再将当前结点设置为后面结点的后续结点。

public class Solution {
public ListNode ReverseList(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode res = ReverseList(head.next);
head.next.next = head;
head.next = null;
return res;
}
}

思路三:
利用栈

import java.util.Stack;

public class Solution {
public ListNode ReverseList(ListNode head) {
if (head == null || head.next == null)
return head;
Stack<ListNode> stack = new Stack<>();
ListNode p = head;
ListNode res = null;
while (p.next != null)
{
stack.push(p);
p = p.next;
}
res = p;
while (!stack.isEmpty())
{
p.next = stack.pop();
p = p.next;
}
p.next = null;
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: