1. 程式人生 > 其它 >leetcode-206翻轉連結串列

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語言解法:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* reverseList(struct ListNode* head){
    struct ListNode *tmp = NULL;
    struct ListNode *prev = NULL;

    while(head != NULL)
    {
        tmp = head->next;
        head->next = prev;
        prev = head;
        head = tmp;
    }
    return prev;
}

結果:

【2】go語言解法:

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func reverseList(head *ListNode) *ListNode {
    var cur *ListNode
    var prev *ListNode
    cur = nil
    prev = nil

    for head != nil{
        cur = head.Next
        head.Next = prev
        prev = head
        head = cur
    }
    return prev
}

結果:

【3】python語言解法:

# 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
        """
        cur,prev = head,None
        while cur:
            cur.next,prev,cur = prev,cur,cur.next
        return prev

結果: