1007. Find the middle element in a Linked List
来源:互联网 发布:mobi漫画制作软件 编辑:程序博客网 时间:2024/05/17 23:05
Assuming the following definition:
template <typename Node_entry>struct Node {
Node_entry entry;
Node *next;
Node();
Node(Node_entry item, Node *add_on = NULL);
};
template <typename Node_entry> Node<Node_entry>::Node()
{
next = NULL;
}
template <typename Node_entry> Node<Node_entry>::Node(Node_entry item, Node *add_on)
{
entry = item;
next = add_on;
}
Implement the following function:
template<typename T> const Node<T>* medianElement( const Node<T> * head )
//Precondition: the linked list head is not empty.(但是需要判断为头空时的情况!)
//Postcondition: it returns the pointer to the middle element in the linked list head.
//If there are even number of elements in the list, the first one of the two middle elements is returned.
For example,
#include <iostream>using namespace std;template <typename Node_entry>struct Node { Node_entry entry; Node *next; Node(); Node(Node_entry item, Node *add_on = NULL);};template <typename Node_entry> Node<Node_entry>::Node(){ next = NULL;}template <typename Node_entry> Node<Node_entry>::Node(Node_entry item, Node *add_on){ entry = item; next = add_on;}template<typename T> const Node<T>* medianElement( const Node<T> * head ) { int count = 0; if (head == NULL) { return head; } const Node<T>* temp = new Node<T>(); temp = head; //计算链表的长度 while (temp != NULL) { count++; temp = temp->next; } //计算出中位数 int half = 1; if (count % 2 == 0) { half = count / 2; } else half = count / 2 + 1; //获得元素 while (half != 1) { head = head->next; half--; } return head;}
- 1007. Find the middle element in a Linked List
- fwnx - find the middle node in the linked list ~~~
- Get middle element of a linked-list
- 【11】Delete a node in the middle of a single linked list
- [CrackCode] 2.3 Delete a node in the middle of a single linked list
- Find the middle point of the linked list
- Ch2-3: remove the middle node in a singly linked list
- find the kth largest element in a list and find the first k largest elements in a list
- LinkedList---Delete Node in the Middle of Singly Linked List
- #372 Delete Node in the Middle of Singly Linked List
- Delete Node in the Middle of Singly Linked List
- Find the nth to last element of a singly linked list
- [CrackCode] 2.2 Find the nth to last element of a singly linked list
- Q2.2 Find the kth to last element of a singly linked list
- To find the kth to Last Element of a Singly Linked List
- Q.2.3 Implement an algorithm to delete a node in the middle of a single linked list, given only acce
- [Haskell] CodeWars|Find the middle element
- Ch2-5: find the beginning of loop in a circular linked list---two solutions
- 软件设计师
- HTML&CSS&JavaScript思维导图
- 泛型类
- hdu 2023 求平均成绩
- reset后的第一条指令
- 1007. Find the middle element in a Linked List
- 如何启动、关闭和设置ubuntu防火墙
- 了解计算机系统
- Ubuntu下如何安装VMWave 10 虚拟机
- biaoti
- 32位汇编——XLAT指令
- appium npm 镜像下载注意
- Web前端开发规范手册
- 不管是哪一种,链接文字都是用 [方括号] 来标记