3. 从尾到头打印链表

 题目:

 

思路:

 

方法1: java实现  性能最差

import java.util.Collections;
import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        //node *p = next;
        ArrayList<Integer> List = new ArrayList<Integer>();
        while(listNode != null){
            List.add(listNode.val);
            listNode= listNode.next;
        }
    Collections.reverse(List); //反转链表
    return List;
    }
}

方法2: java递归

public class Solution {
    ArrayList<Integer> arrayList=new ArrayList<Integer>();
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        if(listNode!=null){
            this.printListFromTailToHead(listNode.next);
            arrayList.add(listNode.val);
        }
        return arrayList;
    }
}

方法3: c++ 链表从尾到头输出,利用递归实现,不使用库函数直接printf输出: 性能最优

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(struct ListNode* head) {
        vector<int> value; //使用向量存储
        if(head != NULL)
        {
            value.insert(value.begin(),head->val);//将val插入value头部;
            if(head->next != NULL)
            {
                vector<int> tempVec = printListFromTailToHead(head->next); //递归调用赋值给tempvec
                if(tempVec.size()>0)
                value.insert(value.begin(),tempVec.begin(),tempVec.end());//将tempvec插入value中 (每次插入头,不用反转)
            }         
             
        }
        return value;
    }
};

 

方法4 :c++ 用库函数,每次扫描一个节点,将该结点数据存入vector中,如果该节点有下一节点,将下一节点数据直接插入vector最前面,直至遍历完,或者直接加在最后,最后调用reverse

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(struct ListNode* head) {
        vector<int> value;
        if(head != NULL)
        {
            value.insert(value.begin(),head->val);
            while(head->next != NULL)
            {
                value.insert(value.begin(),head->next->val);
                head = head->next;
            }         
             
        }
        return value;
    }
};

 

posted @ 2018-11-08 17:51  抒抒说  阅读(275)  评论(0编辑  收藏  举报