描述
输入一个链表,反转链表后,输出新链表的表头。
示例1
输入:
{1,2,3}
复制返回值:
{3,2,1}
核心办法:运用前插法
链表类:
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
方法一:
public class Solution {
public ListNode ReverseList(ListNode head) {
ListNode top = head;//创建新链表接收需要反转的链表(可以直接用head)
ListNode per = null;//反转链表
ListNode next = null;//接收当前要插入结点的下一个结点
while(top != null){
next = top.next;
top.next = per;
per = top;
top = next;
}
return per;
}
}
方法二:
public class Solution {
public ListNode ReverseList(ListNode head) {
ListNode top = null;
while(head != null){
if(top == null){//只有第一步才会执行
top = new ListNode(head.val);//把head第一个点放进去
head = head.next;
}else{
ListNode jud = new ListNode(head.val);//创建新结点获取需要插入的结点
jud.next = top;//把要反转的结点放在新结点后面
top = jud;//把新反转的链表赋给top;
head = head.next;
}
}
return top;
}
}