编程练习001:反转链表(Python|C语言)

题目来源:牛客网

解题思路

  • 指针newHead指向新的已反转的链表的表头;
  • 指针currentHead指向当前原来的链表的表头;
  • 最开始newHead指向原来链表的尾部“空”(NULL/None),currentHead指向原来链表的第一个元素。
例:
最开始:

NULL➡1(currentHead)➡2➡3➡4➡5➡NULL(newHead)

第1次操作:
1(newHead)➡NULL 
2(currentHead)➡3➡4➡5➡NULL
  • 新链表指针指向原链表第一个元素,第一个元素将成为新链表的最后一个元素,故其后指向NULL;当前链表指针头部往后移。
  • 临时指针tmp暂存当前头部的下一个元素(后续将成为新的原链表头部)
  • 在将当前头部变为新链表的头部前,更改当前头部的下一节点,链接新链表的头部(最开始是NULL)
第2次操作:
2(newHead)➡1➡NULL 
3(currentHead)➡4➡5➡NULL
第3次操作:
3(newHead)➡2➡1➡NULL 
4(currentHead)➡5➡NULL
第3次操作:
4(newHead)➡3➡2➡1➡NULL 
5(currentHead)➡NULL
第4次操作:
5(newHead)➡4➡3➡2➡1➡NULL 
currentHead == NULL(结束循环操作)

Python

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    # 返回ListNode
    def ReverseList(self, pHead):
        if pHead == None or pHead.next == None:
            return pHead
        currentHead = pHead
        newHead = None
        while currentHead != None:
            tmp = currentHead.next
            currentHead.next = newHead
            newHead = currentHead
            currentHead = tmp
        return newHead

C

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 */

/**
 * 
 * @param pHead ListNode类 
 * @return ListNode类
 */
struct ListNode* ReverseList(struct ListNode* pHead ) {
    // write code here
    if(pHead == NULL || pHead->next == NULL){
        return pHead;
    }
    
    struct ListNode* newHead = NULL;
    struct ListNode* currentHead = pHead;
    struct ListNode* tmp = NULL;
    while(currentHead != NULL){
        tmp = currentHead->next;
        currentHead->next = newHead;
        newHead = currentHead;
        currentHead = tmp;
    }
    return newHead;
    
}
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值