#include using namespace std;
typedef struct List
{
int Data;
struct List *Pre;//前驱
struct List *Next;//后驱
}ListNode, *ListNodeP;
void InsertNode(ListNodeP &ListHead, ListNodeP &ListTail, int Data)
{
//新创建一个节点
ListNodeP Node = (ListNodeP)malloc(sizeof(ListNode));
Node->Data = Data;
Node->Next = NULL;
//链表头为空,那就把当前新创建的节点初始化给它吧
if (ListHead == NULL)
{
ListHead = Node;
ListHead->Pre = NULL;//此时前驱和后驱都为空
ListTail = ListHead->Pre;
}
else
{
ListNodeP NodeT;
NodeT = ListHead;//取出根节点付给当前结点
while (NodeT->Next)//如果当前结点的后驱不为空,那我们还要继续前进
{
NodeT = NodeT->Next;
}
Node->Pre = NodeT;//把当前链表尾节点付给新创建的节点的前驱(单向链表可不要)
NodeT->Next = Node;//把新创建的节点赋给当前链表尾节点的后驱
ListTail = Node;//更新链表尾部(单向链表可不要)
}
}
void TraveseList(ListNodeP ListHead, ListNodeP ListTail, int Mode)
{
//链表正向遍历
if (Mode == 1)
{
while (ListHead)
{
cout << "Node=" << ListHead->Data << endl;
ListHead = ListHead->Next;
}
}
//链表逆向遍历
else if (Mode == 2)
{
while (ListTail)
{
cout << "Node=" << ListTail->Data << endl;
ListTail = ListTail->Pre;
}
}
}
int main()
{
ListNodeP ListHead = NULL;
ListNodeP ListTail = NULL;
int A[11] = { 24, 6, 18, 3, 7, 17, 20, 2, 4, 13, 65 };
for (int i = 0; i < 11; i++)
{
InsertNode(ListHead, ListTail, A[i]);
}
TraveseList(ListHead, ListTail, 1);
return 0;
}