遍历一个给定数组,创建一个有序链表
2013-10-26 11:07
225 查看
// 遍历数组建立有序链表.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> using namespace std; struct ListNode { int m_nValue; ListNode *m_pNext; }; //创建一个链表,输入从头到尾结点的值,输入-1表示结束 void AddItem(ListNode *&pHead, int nValue) { ListNode *pCur = NULL; ListNode *pPre = NULL; //创建新节点 ListNode *pNewData = new ListNode; pNewData->m_nValue = nValue; pNewData->m_pNext = NULL; if (pHead == NULL) { pHead = pNewData; } else { if (pHead->m_nValue > nValue) { pNewData->m_pNext = pHead; pHead = pNewData; } else { pCur = pHead->m_pNext; pPre = pHead; while (pCur!=NULL && pCur->m_nValue<nValue) { pPre = pCur; pCur = pCur->m_pNext; } pNewData->m_pNext = pPre->m_pNext; pPre->m_pNext = pNewData; } } } //从头到尾打印链表 void PrintList(ListNode *&pHead) { if (pHead != NULL) { ListNode *pCur = pHead; while (pCur != NULL) { cout << pCur->m_nValue << " "; pCur = pCur->m_pNext; } cout << endl; } else { cout << "链表为空!" << endl; } } int _tmain(int argc, _TCHAR* argv[]) { int a[6] = {2,1,4,3,0,9}; ListNode *pHead = NULL; for (int i=0; i<6; i++) { AddItem(pHead, a[i]); } PrintList(pHead); system("pause"); return 0; }
相关文章推荐
- 给定一个有序数组,元素各不相同且升序排列,创建一个高度最小的二叉查找树
- 程序员面试金典: 9.4树与图 4.3给定一个有序整数数组,元素各不相同且按升序排列,创建一颗高度最小的二叉查找树。
- 程序员面试金典: 9.4树与图 4.3给定一个有序整数数组,元素各不相同且按升序排列,创建一颗高度最小的二叉查找树。 ---快速解法
- 【Java】给定一个有序整数数组,元素各不相同且按照升序排列,编写一个算法,创建一个高度最小的二叉查找树
- 给定一个有序整数数组,元素各不相同且按照升序排列,编写一个算法,创建一个高度最小的二叉查找树
- 给定一个有序的数组,元素各不相同且按升序排列,编写一个算法,创建一棵高度最小的二叉查找树?
- 给定一个有序的链表或者数组,构造一棵二叉搜索树
- 给定一个经过一次旋转的有序数组,从中查找一个值,若存在返回它的索引,不存在返回-1
- 给定一个有序数组(递增),写程序构建一棵具有最小高度的二叉树。
- 给定数组,创建(带头节点)的单链表(头插法、尾插法)
- 给定一个经过一次旋转的有序数组,从中查找一个值,若存在返回它的索引,不存在返回-1,假定数组存在重复元素
- Java将两个有序链表合并为一个有序链表、将两个有序数组合并成一个有序数组
- 给定一个值S,在有序数组中找出两个元素A和B,使 A+B = S.
- 链表的基本操作(创建,查找指定位置元素,删除指定元素,插入,倒置,去重,求集合的差,分别交换结点与交换结点值实现的冒泡排序,将两个有序链表合并成一个有序链表)c语言实现
- [Java]给定一个递增有序数组,要求构建一棵具有最小高度的二叉查找树
- 给定一个向量/数组,判定该向量/数组是否为一个二叉搜索数的后续遍历C++
- 给定一个值S,在有序数组中找出两个元素A和B,使 A+B = S.
- 程序员面试金典——解题总结: 9.17中等难题 17.6给定一个整数数组,编写一个函数,找出索引m和n,只要将m和n之间的元素排好序,整个数组就是有序的。注意:n - m越小越好,也就是说,找出
- (旋转数组问题)给定一个整数类型的循环有序数组,求循环数组的特定值,使用二分查找法(JAVA实现)
- Cracking coding interview(4.3)给定一个排好序的数组创建最小高度的二叉树