输入一个链表,反转链表后,输出新链表的表头。
解题思路:
两种方法,大致相同,第一种是在前边随便创建一个节点代替pre进行操作,pre不移动
第二种就是上图展示的做法
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode reverseHead = new ListNode(100);
ListNode current = head;
ListNode next = null;
while(current != null){
next = current.next;
current.next = reverseHead.next;
reverseHead.next = current;
current = next;
}
reverseHead = reverseHead.next;
return reverseHead;
}
public ListNode ReverseList1(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode pre = null;
ListNode next = null;
while(head != null){
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
}