链表的插入、删除、逆序打印、输出倒数第N个、链表逆序

来源:互联网 发布:北风网 人工智能很贵 编辑:程序博客网 时间:2024/05/28 18:42
#include <stdio.h>#include <stdlib.h>#define NotFound-1typedef struct ListNode{int m_Value;struct ListNode *next;} ListNode;//将元素加入到链表的尾部void AddToTrail(ListNode **pHead, int dat){ListNode *pCell = NULL;ListNode *pTemp = NULL;pCell = (ListNode *) malloc(sizeof(ListNode));if (pCell == NULL){printf("Malloc memory failed ...\n");return;}pCell->m_Value = dat;pCell->next = NULL;if ((*pHead) == NULL)*pHead = pCell;else{pTemp = *pHead;while (pTemp->next != NULL)pTemp = pTemp->next;pTemp->next = pCell;}}//删除元素void RemoveNode(ListNode **pHead, int dat){ListNode *pCell = NULL;ListNode *pTemp = NULL;if (pHead == NULL || *pHead == NULL)return;if ((*pHead)->m_Value == dat){pCell = *pHead;*pHead = (*pHead)->next;}else{pTemp = *pHead;while (pTemp->next != NULL && pTemp->next->m_Value != dat)pTemp = pTemp->next;if (pTemp->next != NULL && pTemp->next->m_Value == dat){pCell = pTemp->next;pTemp->next = pCell->next;}}if (pCell != NULL){free(pCell);pCell = NULL;}}//链表元素的逆序输出void ReversePrintListData(ListNode *pHead){if (pHead != NULL){if (pHead->next != NULL)ReversePrintListData(pHead->next);printf("%d\t", pHead->m_Value);}}//释放链表所有元素void FreeListMemory(ListNode **pHead){if (*pHead != NULL){if ((*pHead)->next != NULL)FreeListMemory(&((*pHead)->next));free(*pHead);*pHead = NULL;}}//链表逆序void ReverseList(ListNode **pHead){ListNode *p, *q, *t;if (*pHead == NULL || (*pHead)->next == NULL)return;p = *pHead;q = p->next;p->next = NULL;t = NULL;while (q != NULL){t = q->next;q->next = p;p = q;q = t;}*pHead = p;}//查找链表倒数第N个元素int FindLastNthData(ListNode *pHead, int N){ListNode *pTemp = NULL;ListNode *pCell = NULL;int i = 0;if (pHead == NULL)return NotFound;pTemp = pHead;while (pTemp != NULL && i < N){pTemp = pTemp->next;i++;}if (i == N){pCell = pHead;while (pTemp != NULL){pTemp = pTemp->next;pCell = pCell->next;}return pCell->m_Value;}elsereturn NotFound;}int main(void){ListNode *pHead = NULL;AddToTrail(&pHead, 1);AddToTrail(&pHead, 2);AddToTrail(&pHead, 3);AddToTrail(&pHead, 4);ReversePrintListData(pHead);RemoveNode(&pHead, 1);AddToTrail(&pHead, 5);ReverseList(&pHead);ReversePrintListData(pHead);printf("倒数第1个: %d\n", FindLastNthData(pHead, 1));printf("倒数第2个: %d\n", FindLastNthData(pHead, 2));printf("倒数第3个: %d\n", FindLastNthData(pHead, 3));printf("倒数第4个: %d\n", FindLastNthData(pHead, 4));printf("倒数第5个: %d\n", FindLastNthData(pHead, 5));FreeListMemory(&pHead);return 0;}

0 0
原创粉丝点击