【在线编程】反转链表
【问题描述】
输入一个链表,反转链表后,输出新链表的表头。
【解题思路 & Java实现】
方法一: 前后指针法,原地逆转, 注意最终返回pre。
/*
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 post = null;
while (head != null) {
post = head.next;
head.next = pre;
pre = head;
head = post;
}
return pre;
}
}
方法二:头插法
/*
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 newHead = new ListNode(head.val);
newHead.next = null;
ListNode temp = null;
head = head.next;
while(head != null) {
temp = head;
head = head.next;
temp.next = newHead;
newHead = temp;
}
return newHead;
}
}