zoukankan      html  css  js  c++  java
  • 反转链表

    c++

    栈方法

     1 /*
     2 struct ListNode {
     3     int val;
     4     struct ListNode *next;
     5     ListNode(int x) :
     6             val(x), next(NULL) {
     7     }
     8 };*/
     9 class Solution {
    10 public:
    11     ListNode* ReverseList(ListNode* pHead) {
    12         if(!pHead || !pHead->next) return pHead;
    13         stack<ListNode*> res;
    14         ListNode* p = pHead;
    15         ListNode* newhead;
    16         while(p->next){
    17             res.push(p);
    18             p = p->next;
    19         }
    20         //此时p是最后一个结点
    21         newhead = p;
    22         while(!res.empty()){
    23             p->next = res.top();
    24             p = p->next;
    25             res.pop();
    26         }
    27         //此时p到了反转之后的最后一个结点
    28         p->next = NULL;
    29         return newhead;
    30     }
    31 };

    python

    指针法

     1 # -*- coding:utf-8 -*-
     2 # class ListNode:
     3 #     def __init__(self, x):
     4 #         self.val = x
     5 #         self.next = None
     6 class Solution:
     7     # 返回ListNode
     8     def ReverseList(self, pHead):
     9         # write code here
    10         if pHead==None or pHead.next==None:
    11             return pHead
    12         last = None
    13         cur = pHead
    14         while cur!=None:
    15             temp = cur.next
    16             cur.next = last
    17             last = cur
    18             cur = temp
    19         return last
  • 相关阅读:
    单表查询与多表查询
    我对Jenkins的认识
    Jenkins的使用
    关于CDN的认识
    linux permission denied解决方法
    linux 最近使用的命令
    JVM相关参数的采集
    double 和 float
    BlockingQueue 阻塞队列,很有用的一种
    使用maven打包的注意事项
  • 原文地址:https://www.cnblogs.com/pacino12134/p/11133125.html
Copyright © 2011-2022 走看看