15.反转链表
题目
输入一个链表,反转链表后,输出新链表的表头。
思路
翻转链表并不是很难,只需要注意一下特殊情况,这里设置两个空节点存储前一个结点和后一个结点。
头结点为空直接结束,不为空就开始循环,假设链表为0->1,head=0,next=null,pre=null;然后next=1,head.next=null(最后一位没有子节点),pre=0,head=1;然后next=null,head.next=0,pre=1,head=null,跳出循环,头结点为pre(1),结束。
最后返回的应该是pre不是head,因为原本尾结点现在是pre,多走了一步,head归为null了。
代码
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public ListNode ReverseList(ListNode head) {
if (head == null) {
return null;
}
ListNode pre = null;
ListNode next = null;
while (head != null) {
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}