劍指offer第三天之反轉鏈表

劍指offer第三天之反轉鏈表
輸入一個鏈表,反轉鏈表後,輸出新鏈表的表頭
java:
在這裏插入圖片描述

     /*
data:2020517
author:魏振東
fun:輸入一個鏈表,反轉鏈表後,輸出新鏈表的表頭。
* */
public class Solution {
    public ListNode ReverseList(ListNode head) {
           ListNode r=null;
           ListNode p=null;
        //當前節點是head,p爲當前節點的前一節點,r爲當前節點的下一節點
            while(head!=null)
            {
                r=head.next;
                head.next=p;
                //p向後移動一位,當前節點同樣向後移動一位
                p=head;
                head=r;
            }
            return p;
        
    }
}

c++:
在這裏插入圖片描述

class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        ListNode* r=NULL;
        ListNode* node=pHead;
        ListNode* p=NULL;
        while(node!=NULL)
        {
            r=node->next;
            node->next=p;
            p=node;
            node=r;
        }
        return p;
    }
};

python:
在這裏插入圖片描述

class Solution:
    # 返回ListNode
    def ReverseList(self, pHead):
        # write code here
        t=None;
        p=None;
        while pHead!=None:
            t = pHead.next
            pHead.next = p
            p=pHead
            pHead =t
        return p;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章