版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/huidev/article/details/88546917
思路就是后一个的next 指针指向前一个,然后前一个的next 指向NULL ,,全部完成,实现反转。
// 方法一(非递归):使用栈来完成
public static ListNode reverseList(ListNode head) {
// 如果一开始是空,返回null ;只有一个节点返回那个节点
if (head == null || head.next == null)
return head;
Stack<ListNode> stack = new Stack<>();
while (head.next != null){
stack.push(head);
head = head.next;
}
ListNode node = head;
while (!stack.isEmpty()){
node.next = stack.pop();
node = node.next;
node.next = null;
}
return head;
}
// 方法二(非递归)
public static ListNode reverseList(ListNode head){
ListNode cur = head,pre = null,next = null;
while (cur != null){
next = cur.next; // 下一个不能丢失,因为涉及到链表的断链
cur.next = pre;
pre = cur; // 上一个节点指针不能丢失
cur = next; // 新的当前节点
}
return pre;
}
// 方法三(递归)
public static ListNode reverseList(ListNode head){
if (head == null || head.next == null)
return head;
ListNode node = head.next;
ListNode newNode = reverseList(node);
node.next = head; // next 指向上一个进行反转
head.next = null; // 将新链的尾指向空,断链
return newNode;
}