Reverse a singly linked list.
tag:
遍历链表,然后修改链表的指针,指向其前驱节点。注意当修改链表的next指针时,后继结点会丢失,因此需要保存后继结点。
如图, 定义pre, cur, next
分别指向当前,前驱,后继节点, 则:
while(cur不为空)
纪录后继节点: next = cur.next;
修改当前结点指针: cur.next = pre;
更新pre,cur节点位置: pre = cur; cur = next;
java
public ListNode reverseList(ListNode head) {
ListNode pre = null, next = null;
while(head!=null) {
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
go