交换单向链表的相邻节点
2013-08-13 22:41
330 查看
#include <stdlib.h> #include <stdio.h> //The struct of list node typedef struct Node { int iData; struct Node* pNext; }LNode; /** * Swap the place between two near nodes */ void nearLNodeSwap(LNode** pList) { //Nothing to do in the case of pList is NULL or just has one node if(NULL == pList || NULL == *pList || NULL == (*pList)->pNext) return ; LNode* pre = NULL; LNode* p = *pList; LNode* q = p->pNext; while(p != NULL && q != NULL) { if(p == (*pList)) //Head node { *pList = q; } else //Other nodes { pre->pNext = q; } p->pNext = q->pNext; q->pNext = p; pre = p; p = p->pNext; if(p != NULL) q = p->pNext; } } /** *Create a List and init all of the nodes *pList: the List be created *listSize: list size *return:return list size if success. otherwise return -1 */ int initList(LNode ** pList,const int listSize) { LNode *newNode = NULL; //Init falure and return 0 if(listSize <= 0) return -1; //Init the head element *pList = newNode = (LNode*)malloc( sizeof(LNode) ); if(NULL == newNode) { printf("Error:malloc!\n"); return -1; } newNode->iData = 1; newNode->pNext = NULL; //Init the other elements for(int i = 1; i < listSize; ++i) { newNode->pNext = (LNode*)malloc( sizeof(LNode) ); if(NULL == newNode) { printf("Error:malloc!\n"); return -1; } newNode = newNode->pNext; newNode->iData = i+1; newNode->pNext = NULL; } //Init success and return list size return listSize; } /** *Print the list data *pList: the point of list head */ void printList(LNode* pList) { LNode* pNode = pList; while(NULL != pNode) { printf("%d ",pNode->iData); pNode = pNode->pNext; } printf("\n"); } /** * Destroy the List and release the resources */ void destroyList(LNode** pList) { LNode* pNode; while(NULL != *pList) { pNode = *pList; *pList = (*pList)->pNext; free(pNode); } } int main() { LNode* pList = NULL; initList(&pList,11); printf("Before swap:\n"); printList(pList); //Begin swap the list nearLNodeSwap(&pList); printf("After swap:\n"); printList(pList); destroyList(&pList); getchar(); return 0; }
相关文章推荐
- leetcode24,交换链表相邻的节点
- 交换链表相邻节点
- 交换链表中的相邻节点
- 利用双重指针来实现单向链表的节点交换
- 交换单向链表的头结点和第n个节点
- Java单链表基本操作(九)--交换相邻节点对的值
- leetcode-24,交换链表相邻节点,递归实现
- 交换链表中相邻节点的位置
- 给定一个链表,交换每两个相邻节点并返回其头部。
- 单链表相邻两个节点之间交换顺序
- Swap Nodes in Pairs 链表交换相邻的节点
- (Java) LeetCode 24. Swap Nodes in Pairs —— 两两交换链表中的节点
- 删除单向链表中重复的节点
- 微软面试之13 输入一个单向链表 输出该链表的倒数第k个节点
- 华为OJ从单向链表中删除指定值的节点
- 【链表&交换邻节点】Swap Nodes in Pairs
- 从单向链表中删除指定值的节点
- 两个单向链表的第一个公共节点
- 输出一个单向链表的中间节点
- Leetcode Swap Nodes in Pairs 交换链表的节点对