输入一个链表,从尾到头打印链表每个节点的值。
直接访问链表啊,能有什么问题,然后就RE了,基本功不扎实
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> P;
while(head->next!=NULL){
P.push_back(head->val);
head=head->next;
}
reverse(P.begin(),P.end());
return P;
}
};
这个代码的问题在于,万一压根P就不存在呢?RE
所以我天真的以为加上一个判断语句就行了。
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> P;
if(head==NULL)
return P;
while(head->next!=NULL){
P.push_back(head->val);
head=head->next;
}
reverse(P.begin(),P.end());
return P;
}
};
然后就开心的wa了,为什么呢?
因为当head的next==NULL时候,就停止访问了,那么最后一个就没有存进去啊,我是不是傻。
然后正确的代码
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> P;
while(head!=NULL){
P.push_back(head->val);
head=head->next;
}
reverse(P.begin(),P.end());
return P;
}
};
用了vector的反转函数,也不知道好不好。
这里再附上一个思路的Java代码,因为java中int和Inter不是一个类型,还需要通过构造转换,java中还需要使用Collections类来实现翻转。
import java.util.Collections;
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> P = new ArrayList<Integer>();
while(listNode!=null){
Integer ap=new Integer(listNode.val);
P.add(ap);
listNode=listNode.next;
}
Collections.reverse(P);
return P;
}
}