thảo luận Leetcode mỗi ngày

Python:
class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        prev = None
        cur = head
        while cur is not None:
            temp = cur.next
            cur.next = prev
            prev = cur
            cur = temp           
        return prev
 
Ban đầu xài thêm 1 cái stack, làm xong thấy thằng top làm khôn hơn nên chôm :D
C#:
public class Solution
{
    public ListNode ReverseList(ListNode head)
    {
        ListNode previous = null;
        ListNode it = head;

        while (it != null)
        {
            ListNode next = it.next;
            it.next = previous;
            previous = it;
            it = next;
        }

        return previous;
    }
}
 
Code:
fun reverseList(head: ListNode?): ListNode? {
    var old_head = head;
    var new_head: ListNode? = null;
    while (old_head != null) {
        val next_node = old_head.next;
        old_head.next = new_head;
        new_head = old_head;
        old_head = next_node;
    }
    return new_head;
}

Code:
def reverseList(head: ListNode, prev: ListNode = null): ListNode = {
    if (head == null) {
        prev
    } else {
        reverseList(head.next, ListNode(head.x, prev))
    }
}
 
Last edited:
C#:
public class Solution {
    public ListNode ReverseList(ListNode current, ListNode prev = null)
    {
        if (current == null)
        {
            return prev;
        }

        ListNode next = current.next;
        current.next = prev;
        return ReverseList(next, current);
    }
}
 
Python:
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        prev , curr = None , head
        while curr != None:
            tmp = curr.next
            curr.next = prev
            prev = curr
            curr = tmp
        return prev
 
Java:
    public ListNode reverseList(ListNode head) {
        ListNode current = head;
        ListNode revert = null;
        while(current != null){
            ListNode nodeNext = current.next;
            current.next = revert;
            revert = current;
            current = nodeNext;   
        }
        return revert;
    }
 
Không thể nghĩ đc cách recursion :LOL:) Nhớ hồi sinh viên học môn cấu giải ngay buổi thực hành thứ 2 làm bài này cmnr

Code:
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        prev = None

        while head:
            next_node = head.next
            head.next = prev
            prev = head
            head = next_node
       
        return prev

Recursion thì cần đặt ra 2 câu hỏi:
1. basecase là gì? => khi head == nil, return prev.
2. normal case là gì? => khi head != nil, đổi chiều của head và đẩy trách nhiệm cho hàm recursive sau.

C:
func reverseList(head *ListNode) *ListNode {
    var prev *ListNode
    return reverse(prev, head)
}

func reverse(prev *ListNode, head *ListNode) *ListNode {
    if head == nil {
        return prev
    }
    nxt := head.Next
    head.Next = prev
    return reverse(head, nxt)
}
 
Mấy bài xài ListNode tự định nghĩa như này thì viết hàm test như nào các bác. Bình thường em chỉ dùng 3 hàm này, chả lẽ viết hàm đẩy kết quả vào ArrayList rồi so sánh
ghXpJrI.png

Java:
@Test
public void test() {
    Assertions.assertEquals();
    Assertions.assertArrayEquals();
    Assertions.assertIterableEquals();
}
 
Mấy bài xài ListNode tự định nghĩa như này thì viết hàm test như nào các bác. Bình thường em chỉ dùng 3 hàm này, chả lẽ viết hàm đẩy kết quả vào ArrayList rồi so sánh
ghXpJrI.png

Java:
@Test
public void test() {
    Assertions.assertEquals();
    Assertions.assertArrayEquals();
    Assertions.assertIterableEquals();
}
define input, output ra r assert thôi fen
tui làm bên Go cx dùng như v
Code:
    tests := []struct {
        node *ListNode
        want *ListNode
    }{
        {
            node: &ListNode{Val: 1, Next: &ListNode{Val: 2, Next: &ListNode{Val: 3, Next: &ListNode{Val: 4, Next: &ListNode{Val: 5, Next: nil}}}}},
            want: &ListNode{Val: 5, Next: &ListNode{Val: 4, Next: &ListNode{Val: 3, Next: &ListNode{Val: 2, Next: &ListNode{Val: 1, Next: nil}}}}},
        },
    }

    for index, item := range tests {
        t.Run(fmt.Sprintf("%d", index), func(t *testing.T) {
            output := reverseList(item.node)
            require.Equal(t, item.want, output)
        })
    }
 
Java:
class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) return head;
        return reverseNode(head, null);
    }
    
    private ListNode reverseNode(ListNode head, ListNode prevHead) {
        ListNode nextHead = head.next;
        head.next = prevHead;
        prevHead = head;
        head = nextHead;
        
        if (head == null) return prevHead;
        
        return reverseNode(head, prevHead);
    }
}
 
Bài hôm nay làm rồi, submit lại thôi
JavaScript:
var reverseList = function(head) {
    if (!head) return head;
    let cur = head;
    let prev = null;
    while (cur.next) {
        let next = cur.next;
        cur.next = prev;
        prev = cur;
        cur = next;
    }

    cur.next = prev;

    return cur;
};
 
Code:
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        current = head
        prev = None
        while current != None:
            next = current.next
            current.next = prev
            prev = current
            current = next
        return prev
 
JavaScript:
function reverseList(head: ListNode | null): ListNode | null {
    if (!head || !head.next) {
        return head;
    }

    let newHead: ListNode | null = head;

    while (head && head.next !== null) {
        let nextNode: ListNode = head.next;
        head.next = nextNode.next;
        nextNode.next = newHead;
        newHead = nextNode;
    }

    return newHead;
};
 
JavaScript:
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var reverseList = function(head) {
    let node1 = head;
    let node2 = node1?.next ?? null;

    if (node1?.next) node1.next = null;

    let nextNode = node2;
    while (node2) {
        nextNode = node2.next;
        node2.next = node1;

        node1 = node2;
        node2 = nextNode;
    }

    return node1;
};
 
Linked list ngồi gõ tí là ra :D
Python:
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def isPalindrome(self, head: Optional[ListNode]) -> bool:
        current = head
        count = 0
        while current != None:
            count += 1
            current = current.next
        prev = None
        current = head
        half = count//2
        while half:
            temp = current.next
            current.next = prev
            prev = current
            current = temp
            half -= 1
        if count%2 == 1:
            current = current.next
        
        while prev and current:
            if prev.val != current.val:
                return False
 
            prev = prev.next
            current = current.next
        return True
Python:
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def isPalindrome(self, head: Optional[ListNode]) -> bool:
        slow = head
        fast = head
        while fast.next != None and fast.next.next != None:
            slow = slow.next
            fast = fast.next.next

        secondHalf = slow.next
        slow.next = None
        prev = None
        current = secondHalf
        while current != None:
            temp = current.next
            current.next = prev
            prev = current
            current = temp
          
        first = head
        second = prev
        while first != None and second != None:
            if first.val != second.val:
                return False
          
            first = first.next
            second = second.next
      
        return True
1 thời trẻ trâu ngu dốt =((
1711068559281.png
 
Last edited:
Đảo ngược nửa còn lại, so sánh 2 phần là đc :look_down:
JavaScript:
function isPalindrome(head: ListNode | null): boolean {
    let slow = head, fast = head, prev, temp;
    // fast and slow pointers, when the faster one reaches the tail, the slower one reach the mid
    while (fast && fast.next) {
        slow = slow.next;
        fast = fast.next.next;
    }
    // reverse the back half
    prev = slow, slow = slow.next, prev.next = null;
    while (slow) {
        temp = slow.next
        slow.next = prev
        prev = slow;
        slow = temp;
    }
    // compare value of two linked list
    fast = head, slow = prev
    while(slow) {
        if (fast.val !== slow.val) return false;
        else fast = fast.next, slow = slow.next;
    }
    return true;
};
 
Back
Top