LeetCode[206]反转链表
思路:
这种题一开始我老想着用三个节点来搞,最后发现可以先两个节点试试,然后不行再三个节点,(但还是用三个节点QAQ),要反转链表肯定要搞个虚拟头节点,但是虚拟头节点还不能有数,那就设置虚拟头节点为null就行,然后剩下就是3个节点互相倒,没啥难度
代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre = null, cur = head, temp = null;
while (cur != null) {
temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
}