leetcode-206翻转链表
关注囧囧妹了解更多的编程知识
题目:
-
反转一个单链表。可以迭代或递归地反转链表。
-
示例:输入: 1->2->3->4->5->NULL;输出: 5->4->3->2->1->NULL。
算法说明:
声明两个临时变量tmp和prev,且初始值为NULL;
当遍历节点不为NULL则循环以下四步:
1,将链表要翻转的当前节点的next节点保存到tmp;
2,将当前节点的next节点指向前一个节点prev;
3,更新前一个节点prev为当前节点;
4,更新遍历的节点为tmp;
解法:
【1】C语言解法:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * struct ListNode *next; 6 * }; 7 */ 8 9 10 struct ListNode* reverseList(struct ListNode* head){ 11 struct ListNode *tmp = NULL; 12 struct ListNode *prev = NULL; 13 14 while(head != NULL) 15 { 16 tmp = head->next; 17 head->next = prev; 18 prev = head; 19 head = tmp; 20 } 21 return prev; 22 }
结果:
【2】go语言解法:
1 /** 2 * Definition for singly-linked list. 3 * type ListNode struct { 4 * Val int 5 * Next *ListNode 6 * } 7 */ 8 func reverseList(head *ListNode) *ListNode { 9 var cur *ListNode 10 var prev *ListNode 11 cur = nil 12 prev = nil 13 14 for head != nil{ 15 cur = head.Next 16 head.Next = prev 17 prev = head 18 head = cur 19 } 20 return prev 21 }
结果:
【3】python语言解法:
1 # Definition for singly-linked list. 2 # class ListNode(object): 3 # def __init__(self, x): 4 # self.val = x 5 # self.next = None 6 7 class Solution(object): 8 def reverseList(self, head): 9 """ 10 :type head: ListNode 11 :rtype: ListNode 12 """ 13 cur,prev = head,None 14 while cur: 15 cur.next,prev,cur = prev,cur,cur.next 16 return prev
结果: