Leetcode - 876. Middle of the Linked List

想法:

cur 就是一直往下尋訪

pos 用來記錄目前 cur 尋訪到的節點位置 (從0開始, 0, 1, 2, 3...)

pos & 1 是用來判斷奇數偶數 (用 bit 來判斷)

mid 則是在碰到"尋訪到第奇數個"時才會往下尋訪


Code:

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

Node* middleNode(Node* head){
    Node* cur;
    Node* mid;
    cur = head;
    mid = cur;
    int pos = 0;
    if(cur == NULL){
        return NULL;
    }
    while(cur != NULL){
        if(pos & 1){
            mid = mid->next;
        }
        pos++;
        cur = cur->next;
    }
    return mid;    
}


留言

這個網誌中的熱門文章

Formal Verification(正規驗證)介紹和如何使用 SVA(System Verilog Assertion) 做驗證

Quartus Qsys + Nios II 入門使用

Algorithm - Sorting (Insertion Sort) 插入排序法