题目描述:输入一个链表,反转链表后,输出新链表的表头
解题思路:方法一、定义三个指针,第三个指针用来防止断链
方法二、定义一个新节点,采用头插的思想进行反转
一、三指针方法
/*
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 || head.next == null){
return head;
}
ListNode left = head;
ListNode mid = left.next;
ListNode right = mid.next;
while(right != null){
mid.next = left;
left = mid;
mid = right;
right = right.next;
}
mid.next = left;
head.next = null;
head = mid;
return head;
}
}
二、头插法思想
第二种方法是不断在原链表中去掉头节点,然后将去掉的节点头插到新头节点中
/*
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 || head.next == null){
return head;
}
ListNode new_head = null;
while(head != null){
ListNode p = head;
head = head.next;
p.next = new_head;
new_head = p;
}
return new_head;
}
}