給定一個單鏈表,找到連結串列的中間。例如,如果給定的連結串列是1-> 2-> 3-> 4-> 5,則輸出應為3。 如果有偶數節點,則將有兩個中間節點,我們需要列印第二個中間節點元件。例如,如果給定的連結串列為1-> 2-> 3-> 4-> 5-> 6,則輸出應為4。
方法1: 遍歷整個連結串列,並計數。節點。現在再次遍歷列表,直到count / 2並返回count / 2處的節點。
方法2: 使用兩個指標遍歷連結串列。將一個指標移動一個,將另一個指標移動兩個。當快速指標到達末尾時,慢速指標將到達連結串列的中間。
下圖顯示了printMiddle函式如何在程式碼中工作:
C ++:
#include<bits/stdc++.h> using namespace std; struct Node { int data; struct Node* next; }; void printMiddle(struct Node *head) { struct Node *slow_ptr = head; struct Node *fast_ptr = head; if (head!=NULL) { while (fast_ptr != NULL && fast_ptr->next != NULL) { fast_ptr = fast_ptr->next->next; slow_ptr = slow_ptr->next; } printf("The middle element is [%d]\n\n", slow_ptr->data); } } void push(struct Node** head_ref, int new_data) { struct Node* new_node = new Node; new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node; } void printList(struct Node *ptr) { while (ptr != NULL) { printf("%d->", ptr->data); ptr = ptr->next; } printf("NULL\n"); } int main() { struct Node* head = NULL; for (int i=5; i>0; i--) { push(&head, i); printList(head); printMiddle(head); } return 0; }
C
#include<stdio.h> #include<stdlib.h> /* Link list node */struct Node { int data; struct Node* next; }; void printMiddle(struct Node *head) { struct Node *slow_ptr = head; struct Node *fast_ptr = head; if (head!=NULL) { while (fast_ptr != NULL && fast_ptr->next != NULL) { fast_ptr = fast_ptr->next->next; slow_ptr = slow_ptr->next; } printf("The middle element is [%d]\n\n", slow_ptr->data); } } void push(struct Node** head_ref, int new_data) { struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node; } void printList(struct Node *ptr) { while (ptr != NULL) { printf("%d->", ptr->data); ptr = ptr->next; } printf("NULL\n"); } int main() { struct Node* head = NULL; int i; for (i=5; i>0; i--) { push(&head, i); printList(head); printMiddle(head); } return 0; }
方法3: 將mid元素初始化為head並將一個計數器初始化為0。從head遍歷該列表,同時遍歷該計數器,並在計數器為奇數時從中到中> next。因此,中間部分只會移動列表總長度的一半。 感謝Narendra Kangralkar提出了這種方法。
#include <bits/stdc++.h> using namespace std; struct node { int data; struct node* next; }; void printMiddle(struct node* head) { int count = 0; struct node* mid = head; while (head != NULL) { if (count & 1) mid = mid->next; ++count; head = head->next; } if (mid != NULL) printf("The middle element is [%d]\n\n", mid->data); } void push(struct node** head_ref, int new_data) { struct node* new_node = (struct node*)malloc( sizeof(struct node)); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node; } void printList(struct node* ptr) { while (ptr != NULL) { printf("%d->", ptr->data); ptr = ptr->next; } printf("NULL\n"); } int main() { struct node* head = NULL; int i; for(i = 5; i > 0; i--) { push(&head, i); printList(head); printMiddle(head); } return 0; }
C:
最新評論