反转链表
leetcode206题
建立虚拟头节点辅助反转
第一反应,顺序遍历链表,每个节点用头插法,插入到新链表的头部,即可实现反转
为了方便后续循环操作,先从原链表摘出头节点,作为新链表的头节点
public ListNode reverseList(ListNode head) {
if(head == null) return null;
ListNode newlist;
ListNode current = head;
//先向新节点加入一个节点
newlist = head;
head = head.next;
current.next = null;
current = head;
//开始头插法
while(head != null) {
head = head.next;
current.next = newlist;
newlist = current;
current = head;
}
return newlist;
}
直接操作链表实现反转
大概看了一眼解析,类似于用三个指针,指向相邻的三个节点,然后通过指针直接调转三个节点的next
还是画个图吧
public ListNode reverseList(ListNode head) {
if(head == null) return null;
if(head.next == null) return head;
ListNode pre = head, cur = head.next, next = head.next.next;
//将头节点的指针置为null
pre.next = null;
//结合图理解
cur.next = pre;
while(next != null) {
//三个指针后移
pre = cur;
cur = next;
next = next.next;
//反转cur方向
cur.next = pre;
}
ListNode ans = cur;return ans;
}
要注意边界问题,em另外看了答案的代码,发现自己写的有点傻,又有边界问题,思路又不简洁
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNodd curr = head;
while(curr != null) {
//在反转cur节点之前先给next赋值
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}