题目描述:
输入一个链表,反转链表后,输出链表的所有元素。
解题思路:
由于链表的顺序存储特性,必须遍历各结点才能完成反转。
首先创建两个结点,一个指向当前结点,另一个指向下一个结点。要做的就是使下一个结点指向当前结点,然后当前结点赋值为下一个结点,下一个结点赋值为下下个结点。有点类似斐波那契数列的计算过程。
附上代码:
public class Solution {
public ListNode ReverseList(ListNode head) {
ListNode curr = null;
ListNode follow = head;
if(head == null){
return null;
}
while(follow!=null){
ListNode temp = follow.next;
follow.next = curr;
curr = follow;
follow = temp;
}
return curr;
}
}
性能结果:
运行时间:16ms,所占内存:8870K
优秀解法:
该题的解决思想貌似只有这一种,具体代码实现细节的不同会稍微影响代码的性能,但没有明显优于其他的解法。
不过在浏览解法时发现了一种C++的解决方案,采用了递归的方法,附上代码:
class
Solution {
public
:
ListNode* ReverseList(ListNode* pHead) {
//如果链表为空或者链表中只有一个元素
if
(pHead==NULL||pHead->next==NULL)
return
pHead;
//先反转后面的链表,走到链表的末端结点
ListNode* pReverseNode=ReverseList(pHead->next);
//再将当前节点设置为后面节点的后续节点
pHead->next->next=pHead;
pHead->next=NULL;
return
pReverseNode;
}
};