核心思路:用三个指针,分别是head,prev,next。
(1)C语言代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head) {
struct ListNode* prev = NULL;
while(head!=NULL){
struct ListNode* next = head->next;
head->next = prev;
prev = head;
head = next;
}
return prev;
}
(2)C++语言代码:
/**
* 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) {
if(head == NULL){
return head;
}
ListNode* prev = NULL;
while(head!=NULL){
ListNode* next = head->next;
head->next = prev;
prev = head;
head = next;
}
return prev;
}
};
(3)java语言代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
while(head!=null){
ListNode next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}
}