反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULLc++:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *newHead=NULL;
while(head){
ListNode *next=head->next;
head->next=newHead;
newHead=head;
head=next;
}
return newHead;
}
};
python:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
newHead=None
while head!=None:
nxt=head.next
head.next=newHead
newHead=head
head=nxt
return newHead
java:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode newHead=null;
while(head!=null){
ListNode next=head.next;
head.next=newHead;
newHead=head;
head=next;
}
return newHead;
}
}
原文:https://www.cnblogs.com/mcq1999/p/11717051.html