一、题目
输入一个链表,反转链表后,输出新链表的表头。
二、分析及代码
1. 三指针
(1)思路
设计三个指针,分别指向前一结点、当前结点和后一结点,依次对链表进行处理。
(2)代码
public class Solution {
public ListNode ReverseList(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode preNode = head;
ListNode node = head.next;
ListNode nextNode = node.next;
head.next = null;
while (nextNode != null) {
node.next = preNode;
preNode = node;
node = nextNode;
nextNode = nextNode.next;
}
node.next = preNode;
return node;
}
}
(3)结果
运行时间:27ms,占用内存:9396k。
三、其他
暂无。