- 这几天做了下反转链表。leetcode上的206题。感觉他那个题有问题。搞了几个小时也AC不了。后来发现是题目描述有问题。题目说头结点,头结点其实是不带数据的。但206题其实是带数据的头结点,可以直接通过print打印head.val的值,发现是1。
那么接下来通过两种思路来解题。
方法一:双指针
public static ListNode reverseList(ListNode head){
ListNode cur = head;
ListNode pre = null;
ListNode temp = null;
while (cur != null){
temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
方法二:头插法(头结点不含数据)
public static ListNode reverseList(ListNode head) {
if (head.next == null ||head.next.next ==null)
return head;
ListNode cur = head.next;
ListNode cNext = null;
ListNode reverseHead = new ListNode();
while (cur != null){
cNext = cur.next;
cur.next = reverseHead.next;
reverseHead.next = cur;
cur = cNext;
}
head = reverseHead;
return head;
}
头结点包含数据 206 的一种题解:
public ListNode reverseList(ListNode head) {
if(head == null){
return head;
}
if (head.next == null)
return head;
ListNode cur = head;
ListNode cNext = null;
ListNode reverseHead = new ListNode();
while (cur != null){
cNext = cur.next;
cur.next = reverseHead.next;
reverseHead.next = cur;
cur = cNext;
}
head = reverseHead.next;
return head;
}