反转链表

题目:反转链表

分析:拿到这种题,一般先要知道链表这种结构,然后知道怎样遍历链表,这题比较简单,题眼在反转上,那么我第一个想到用栈这种数据结构来存储

思路:依次遍历链表将元素存入栈中,然后出栈,就得到相应的链表反转后的数据了


C++代码:

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
         
        if(pHead==NULL||pHead->next==NULL){
            return pHead;
        }
             
        stack<ListNode *> s;
        ListNode *node = pHead;
        ListNode *list;
        while(node->next!=NULL){
            s.push(node);
            node = node->next;
        }
        list = node;
        while(!s.empty()){
            node->next = s.top();
            node = node->next;
            s.pop();
        }
        node->next = NULL;
        return list;
        
    }
     
};

Java代码:

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
import java.util.Stack;
import java.util.*;
public class Solution {
    public ListNode ReverseList(ListNode head) {
        if(head==null || head.next==null){
            return head;
        }
        Stack<ListNode> s = new Stack<ListNode>();
        ListNode p = head;
        ListNode l;
        while(p.next!=null){
            s.push(p);
            p = p.next;
        }
        l=p;
        while(!s.empty()){
            p.next=s.peek();
            p=p.next;
            s.pop();
        }
        p.next=null;
        return l;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值