剑指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;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章