Reverse a singly linked list.
思路:
注意几个地方:
变换前: h ----> i ----> j
变换后: h <---- i <---- j
1 以i节点为当前节点。假设i节点前面的节点都实现了逆转。现在已i节点为参考对象。注意需要用一个新定义的ListNode去记录下i的下一个节点j。因为如果单纯的将j的下一节点指向h,会导致i , j 之间断裂。
2 使用循环迭代的方法得到当前节点的前一结点是很常用的得到前一结点的方法。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseList(ListNode head) {
ListNode pReverseHead = null;
ListNode pNext = null;
ListNode pPre = null;
ListNode pNode = head;
while(pNode != null) {
pNext = pNode.next;
if(pNext == null) {
pReverseHead = pNode;
}
pNode.next = pPre;
pPre = pNode;
pNode = pNext;
}
return pReverseHead;
}
}
每次写完代码,都需要用几类测试用例对代码进行功能测试。
1 输入的链表头指针为Null。
2 输入的链表只有一个节点。
3 输入的链表有多个节点。
只有确信代码能够通过这3类测试用例的测试,才能保证代码的正确性。