算法
Java
Leetcode
Golang
Reverse a singly linked list.
Question
Reverse a singly linked list.See it on Leetcode
1
2
3
For example,
Assume that we have linked list 1 → 2 → 3 → Ø
We would like to change it to Ø ← 1 ← 2 ← 3
Hint
A linked list can be reversed either iteratively or recursively . Could you implement both?
Solution in iteratively approach 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public ListNode reverseList (ListNode head) { ListNode prev = null ; ListNode curr = head; while (curr != null ) { ListNode nextTemp = curr.next; curr.next = prev; prev = curr; curr = nextTemp; } return prev; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 * 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* prev = NULL ; ListNode* curr = head; while (curr != NULL ) { ListNode* nextTemp = curr->next; curr->next = prev; prev = curr; curr = nextTemp; } return prev; } };
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func reverseList (head *ListNode) *ListNode { var prev *ListNode curr := head for curr != nil { nextTemp := curr.Next curr.Next = prev prev = curr curr = nextTemp } return prev }
Solution in recursively approach 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 * 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) { if (head == null || head.next == null ) return head; ListNode p = reverseList(head.next); head.next.next = head; head.next = null ; return p; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 * 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 || head->next == NULL ) return head; ListNode* p = reverseList(head->next); head->next->next = head; head->next = NULL ; return p; } };
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func reverseList (head *ListNode) *ListNode { if (head == nil || head.Next == nil ) { return head } p := reverseList(head.Next) head.Next.Next = head head.Next = nil return p }