牛客題霸 BM1 反轉鏈表(C#、C++)
簡單 通過率:38.76% 時間限制:1秒 空間限制:256M
知識點鏈表
描述
給定一個單鏈表的頭結點pHead(該頭節點是有值的,比如在下圖,它的val是1),長度為n,反轉該鏈表后,返回新鏈表的表頭。
數據范圍: 0\leq n\leq1000
要求:空間復雜度 O(1) ,時間復雜度 O(n) 。
如當輸入鏈表{1,2,3}時,
經反轉后,原鏈表變為{3,2,1},所以對應的輸出為{3,2,1}。
以上轉換過程如下圖所示:
示例1
輸入:
{1,2,3}
返回值:
{3,2,1}
示例2
輸入:
{}
返回值:
{}
說明:
空鏈表則輸出空
using System;
using System.Collections.Generic;
/*
public class ListNode {
public int val;
public ListNode next;
public ListNode (int x) {
val = x;
}
}
*/
class Solution {
/**
* 代碼中的類名、方法名、參數名已經指定,請勿修改,直接返回方法規定的值即可
*
*
* @param head ListNode類
* @return ListNode類
*/
public ListNode ReverseList (ListNode head) {
if(head==null)return null;
ListNode next = head.next;
ListNode cur = head;
ListNode temp;
head.next = null;
while (next != null) {
temp = next.next;
next.next = cur;
cur = next;
next = temp;
}
return cur;
}
}
浙公網安備 33010602011771號