leetcode-206-Reverse-Linked-List

描述


Reverse a singly linked list.

分析


meh,画图。

解决方案1(Python)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None:
return
result_node = [None, head]
while True:
if result_node[-1].next is not None:
result_node.append(result_node[-1].next)
else:
break
for i in range(1, len(result_node)):
result_node[i].next = result_node[i-1]
return result_node[-1]

解决方案2(C++)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* 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) {
ListNode* pivot = head;
ListNode* frontier = NULL;
while(pivot!=NULL && pivot->next!=NULL){
frontier = pivot->next;
pivot->next = pivot->next->next;
frontier->next = head;
head = frontier;
}
}
return head;
}
};

解决方案3(Java)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* 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) {
ListNode pivot = head;
ListNode frontier = null;
while(pivot!=null && pivot.next!=null){
frontier = pivot.next;
pivot.next = pivot.next.next;
frontier.next = head;
head = frontier;
}
}
return head;
}
}

解决方案4(Golang)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func reverseList(head *ListNode) *ListNode {
var pre *ListNode = nil

current := head
for nil != current {
now := current.Next
current.Next = pre
pre = current
current = now
}
return pre
}

相关问题


题目来源