代码思路:
使用头插法插入:
当前节点是head,pre为当前节点的前一节点,next为当前节点的下一节点
需要pre和next的目的是让当前节点从pre->head->next1->next2变成pre<-head next1->next2
即pre让节点可以反转所指方向,但反转之后如果不用next节点保存next1节点的话,此单链表就此断开了
所以需要用到pre和next两个节点
1->2->3->4->5
1<-2<-3 4->5
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head == null)
return null;
ListNode pre = null; //当前结点的前一个结点
ListNode last = null; //当前结点的后一个结点
while(head != null)
{
last = head.next;
//先保存head.next信息,不然会丢失。若先head.next=pre,则head.next信息丢失
head.next = pre; //
pre = head;
head = last;//pre和head各向后移动一位
}
return pre;
}
}
思路二:利用栈的特性
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>();
while(head!=null && head.next != null)
{
stack.push(head);
head = head.next;
}
ListNode dummylast = stack.peek();//dummylast是倒数第二个结点
ListNode lastnode = dummylast.next;//取最后一个元素作为头结点
ListNode newHead = lastnode;
while(!stack.isEmpty())
{
lastnode.next = stack.peek();
lastnode = lastnode.next;
stack.pop();
}
lastnode.next = null;//最后一个结点应该置位null
return newHead;
}
}
思路三:递归
import java.util.Stack;
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head == null || head.next == null)//若链表为空或者只有一个结点
return head;
ListNode newHead = ReverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
}