小鱼儿_单链表倒置
数据结构自己自学了一些。这期才开的课。
老师布置的作业。。。
简单写了一下
程序代码:// Note:Your choice is C++ IDE
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
#define DateType int
typedef struct tagListNode
{
DateType date;
struct tagListNode *next;
}ListNode;
typedef struct tagListInfo
{
ListNode* head;
ListNode* tail;
int num;
}ListInfo;
typedef struct tagList
{
void *lpr; //私有数据不给用户操作
}List;
int CreateList(List &l)
{
ListInfo * li = NULL;
l.lpr = (ListInfo*)malloc(sizeof(ListInfo));
if(l.lpr == NULL)
{
cout<<"非法数据"<<endl;
return 0;
}
li = (ListInfo*)l.lpr;
li->head = NULL;
li->tail = NULL;
li->num = 0;
return 1;
}
int ListAdd(List &l,DateType date)
{
ListInfo* li = NULL;
ListNode* CurPtr = NULL;
li = (ListInfo*)l.lpr;
CurPtr = (ListNode*)malloc(sizeof(ListInfo));
if(NULL == CurPtr)
{
cout<<"内存申请失败"<<endl;
return 0;
}
CurPtr->date = date;
CurPtr->next = NULL;
if(NULL == li->head)
{
li->head = CurPtr;
li->tail = CurPtr;
li->num++;
}
else
{
li->tail->next = CurPtr;
li->tail = CurPtr;
li->num++;
}
return 1;
}
void ListShow(List &l)
{
ListInfo* li = NULL;
li = (ListInfo*)l.lpr;
ListNode* CurPtr = NULL;
CurPtr = li->head;
while(CurPtr)
{
cout<<(CurPtr->date)<<"\t";
CurPtr = CurPtr->next;
}
}
//主要功能函数:把一个链表的重置(这里是调用指针的形式进行)
//主要是用到3个指针 :: p 代表prePtr c 代表 CurPtr t 代表 tempHead
// 0 1 2 3 4 5 6 7 8 9 10
// p c t
// 0 1 2 3 4 5 6 7 8 9 10
// p c t
//这样3个指针移动修改指针的指向就可以了。
//具体细节看代码
void ListRever(List &l)
{
ListInfo* li = NULL;
ListNode* temp = NULL;
ListNode* CurPtr = NULL;
//放原来的头尾结点的位置
ListNode* tempHead = NULL;
ListNode* tempTail = NULL;
li = (ListInfo*)l.lpr;
if(li->head == NULL)
{
puts("头不能为空");
return;
}
tempHead = li->head->next;
CurPtr = tempHead;
tempTail = li->head;
ListNode* pRePtr = li->head;
while(tempHead)
{
tempHead = tempHead->next;
CurPtr->next = pRePtr;
temp = CurPtr;
CurPtr =tempHead;
pRePtr = temp;
}
tempTail->next = NULL; //注意一定要 不然出现问题
li->head = pRePtr; //这里pRePtr 移到最后是运行到原来链表的尾部
li->tail = tempTail;
}
int main()
{
int date[100] = {0};
List l;
CreateList(l);
for(int i=0;i<100;i++)
{
ListAdd(l,i);
}
ListShow(l);
puts("\n就要进行重置了");
ListRever(l);
ListShow(l);
return 0;
}








