1.剑指offer系列:从尾到头打印链表

Java实现方式

描述

输入一个链表,按链表从尾到头的顺序返回一个ArrayList。

代码

/**
*    public class ListNode {
*        int val;
*        ListNode next = null;
*
*        ListNode(int val) {
*            this.val = val;
*        }
*    }
*
*/
import java.util.*;
public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
/*      //根据方法返回值类型,首先可以想到头插ArrayList的方法
        ArrayList<Integer> list = new ArrayList<Integer>();
        while(listNode != null){
            list.add(0,listNode.val);
            listNode = listNode.next;
        }
        return list;
*/
/*      //根据栈后进先出的特点实现
        ArrayList<Integer> list = new ArrayList<Integer>();
        Stack<Integer> stack = new Stack<Integer>();
        while(listNode != null){
            stack.push(listNode.val);
            listNode = listNode.next;
        }
        while(!stack.isEmpty()){
            list.add(stack.pop());
        }
        return list;
*/
        //递归,每访问一个结点的时候,先递归输出它后面的结点
        ArrayList<Integer> list = new ArrayList<Integer>();
        if(listNode != null){
            list = printListFromTailToHead(listNode.next);
            list.add(listNode.val);
        }
        return list;     
    }
}





C++实现方式1.递归

思路

  1. 设计一个函数:递归反转链表先,然后调整递归的代码;
  2. 然后把链表的值插入到数组;

/**

 * Definition for singly-linked list.

 * struct ListNode {

 *     int val;

 *     ListNode *next;

 *     ListNode(int x) : val(x), next(NULL) {}

 * };

 */

class Solution {

public:

    vector<int> reversePrint(ListNode* head) {

        vector<int> v; //用来存放链表的值

//递归得到反转后的链表

        ListNode* newHead =  reverse(head);

//插入反转后的链表的值入数组v

        ListNode* cur =newHead;

        while(cur !=NULL){

            v.push_back(cur->val);

            cur = cur->next;

        }

        return v;

    }

private:

//反转函数

    ListNode* reverse(ListNode* head){

//如果链表为空或者只有一个结点,直接返回头指针

       if(head == NULL  || head->next == NULL){           

           return head;

        }

        //递归调用head->next后面的链表

        ListNode* newHead = reverse(head->next);

        //调整递归后的链表

        //head->next->next是指向最后一个结点的指针

        head->next->next = head;

        //修改最后一个结点的指针为NULL

        head->next = NULL;

        //返回新的头结点

        return newHead;

    }

};

 

2.头插法实现思路及其实现代码

思路:

头插时候,先处理要头插数据的下一个结点,所以要保存将要头插结点的指针定义一个临时指针temp = head->next; 于此同时定义一个新指针 newHead = NULL;
处理将要头插的数据:即head = newHead;
处理头插前面的结点:newHead ->next = head;
处理结束后:旧头结点继续往前移动 head = temp;
开始插入数据入数组!

/**

 * Definition for singly-linked list.

 * struct ListNode {

 *     int val;

 *     ListNode *next;

 *     ListNode(int x) : val(x), next(NULL) {}

 * };

 */

class Solution {

public:

    vector<int> reversePrint(ListNode* head) {

        vector<int> v;

        ListNode* newHead =  reverse(head);

        ListNode* cur =newHead;

        

        while(cur !=NULL){

            v.push_back(cur->val);

            cur = cur->next;

        }

 

        return v;

    }

private:

    ListNode* reverse(ListNode* head){

 

        if(head == NULL  || head->next == NULL){           

            return head;

        }

       ListNode* newHead = NULL;

       //让头指针遍历链表进行头插

       while(head !=NULL){

           ListNode* temp = head->next;

           head->next = newHead;

           newHead = head;

           head = temp;

       }           

        return newHead;

    }

};

 

3.栈模拟思路及其代码实现

思路:
由于栈的先进后出和这里的从尾打印链表刚好吻合,所以可以用栈来完成。

/**

 * Definition for singly-linked list.

 * struct ListNode {

 *     int val;

 *     ListNode *next;

 *     ListNode(int x) : val(x), next(NULL) {}

 * };

 */

class Solution {

public:

    vector<int> reversePrint(ListNode* head) {

         stack<int> stk;

        vector<int> v;

        //开始入栈

        while(head != NULL){

            stk.push(head->val);

            //链表迭代往下走

            head = head->next;

        }

        //开始出栈到数组

        while(!stk.empty()){

            v.push_back(stk.top());

            stk.pop(); //记得弹栈

        }

        return v;

    }  

};

 打印示例

1、“后进先出”,可以用栈实现这种顺序

#include <iostream>

#include <stack> 

using namespace std;

 

struct ListNode

{

    int m_nValue;

    ListNode* m_pNext;

};

 

void PrintReversingly(ListNode* pHead)

{

    std::stack<ListNode*> nodes ;

    ListNode* pNode = pHead;

    while(pNode != NULL)

    {

        nodes.push(pNode);

        pNode = pNode->m_pNext;

    }

    while(!nodes.empty())

    {

        pNode = nodes.top();

        printf("%d\t",pNode->m_nValue);

        nodes.pop();

    }

}

 

int main(void) {

    struct ListNode a ={1,NULL},b={4,NULL},c={3,NULL},d={9,NULL};

    a.m_pNext = &b;

    b.m_pNext = &c;

    c.m_pNext = &d;

    PrintReversingly(&a);

    return 0;

}

 

2、递归:在本质就是一个栈结构

#include <iostream>

#include <stack> 

using namespace std;

 

struct ListNode

{

    int m_nValue;

    ListNode* m_pNext;

};

 

void PrintReversingly(ListNode* pHead)

{

    if(pHead != NULL)

    {

        if(pHead->m_pNext != NULL)

        {

            PrintReversingly(pHead->m_pNext);

        }

        printf("%d\t", pHead->m_nValue);

    }

}

 

int main(void) {

    struct ListNode a ={1,NULL},b={4,NULL},c={3,NULL},d={9,NULL};

    a.m_pNext = &b;

    b.m_pNext = &c;

    c.m_pNext = &d;

    PrintReversingly(&a);

    return 0;

}

 
 
 
 
 

 

php 从尾到头打印链表,PHP从尾到头打印链表实例讲解

//递归版本

function printListFromTailToHead($head)

{

  if($head == NULL){

  return [];

  }

  $arr = array();

  $cur = $head;

  if($cur->next != null){

    $arr = printListFromTailToHead($cur->next);

  }

  array_push($arr, $cur->val);

  return $arr;

}

//非递归版本

function printListFromTailToHead($head)

{

  if($head == NULL){

  return [];

  }

  $cur = $head;

  $arr = array();

  $re = array();

  while($cur != NULL){

    array_push($arr, $cur->val);

    $cur = $cur ->next;

  }

  while(!empty($arr)){

    $tmp = array_pop($arr);

    array_push($re, $tmp);

  }

  return $re;

}

 

<?php
class Node{
        public $data;
        public $next;
}
//创建一个链表
$linkList=new Node();
$linkList->next=null;
$temp=$linkList;
for($i=1;$i<=10;$i++){
        $node=new Node();
        $node->data="aaa{$i}";
        $node->next=null;
        $temp->next=$node;
        $temp=$node;
}
function printListFromTailToHead($linkList){
        $arr=array();
        $p=$linkList;
        while($p->next!=null){
                $p=$p->next;
                array_unshift($arr,$p->data);
        }
        return $arr;
}
$arr=printListFromTailToHead($linkList);
var_dump($arr);

 

剑指offer——python【第1题】从尾到头打印链表

 

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # 返回从尾部到头部的列表值序列,例如[1,2,3]
    def printListFromTailToHead(self, listNode):
        list=[]
        while listNode:
            list.append(listNode.val)
            listNode = listNode.next
        return list[::-1]



////////

# -*- coding: utf-8 -*-

"""

Created on Sat Oct 14 18:57:34 2017

@author: gb_xiao

Mail: mingliumengshao@163.com

"""

 

"""

题目描述:

输入一个链表,从尾到头打印链表每个节点的值。

"""

 

class ListNode():

#链表的构造 初始化

    def __init__(self, x):

        self.val = x

        self.next = None

 

def CreateList(n):

#链表的创建

    if n <= 0:

        return False

    if n == 1:

        return ListNode(1)

    else:

        listNode = ListNode(1)

        tmp = listNode

        for i in range(2,n+1):

            tmp.next = ListNode(i)

            tmp  = tmp.next

    return listNode

 

def PrintList(listNode):

#用以打印链表结点

    tmp = listNode

#不要改变原来的链表

    while tmp:

        print tmp.val

        tmp = tmp.next

        

def function1(listNode):

    lists = []

    while listNode:

        lists.append(listNode.val)

        listNode = listNode.next

    return lists[::-1]        

 

def function2(listNode):

    lists = []

    while listNode:

        lists.append(listNode.val)

        listNode = listNode.next

    lists.reverse()

    return lists 

 

def main():

    listNode = CreateList(11)

    #打印链表进行测试

#    PrintList(listNode)

    print function1(listNode)

    

 

if __name__ == "__main__":

    main()

========================================================================================
 
 
 
 



 

posted @ 2022-08-18 11:49  sundaysc++  阅读(21)  评论(0编辑  收藏  举报