题目:输入一个链表,反转链表。
给定的结点结构:
class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
我的想法是:用三个结点first,head,second分别来表示前一个结点,当前结点,和后一个结点。三个结点的初始状态:first为null,head为第一个结点,second为第二个结点,三个结点同步移动,每移动一次,便将head的next由原来的指向second改为指向first,这样当second为null时,head刚好处于最后一个结点。
代码如下:
public ListNode ReverseList(ListNode head) {
ListNode first, second;
if (head == null) return null;
first = null;
second = head.next;
head.next = first;
while (second != null) {
first = head;
head = second;
second = second.next;
head.next = first;
}
return head;
}
原文:https://www.cnblogs.com/yi-hui/p/8877327.html