标签:数据结构
题目:输入一个链表的头结点,反转该链表,并返回反转后链表的头结点。链表结点定义如下:
struct ListNode
{
int m_nKey;
ListNode* m_pNext;
};
c语言实现
/* File : rlink.c Author : Date : 2015/4/4 platform : windows7 x86_64 version : 1.0 Function : 反转一个链表 */ #include <stdio.h> #include <stdlib.h> typedef struct _LinkNode { int m_nKey; struct _LinkNode* m_npNext; }LinkNode , *pLinkNode; /* 创建链表 以0结尾 */ pLinkNode create() { pLinkNode pHead = NULL , pCur , pNext; int nData; if(scanf("%d" , &nData) , nData) { pHead = (pLinkNode)malloc(sizeof(LinkNode)); pCur = pNext = pHead; pHead->m_nKey = nData; pNext->m_npNext = NULL; } else { return NULL; } while(scanf("%d" , &nData) , nData) { pNext = (pLinkNode)malloc(sizeof(LinkNode)); pNext->m_nKey = nData; pCur->m_npNext = pNext; pCur = pNext; pNext->m_npNext = NULL; } return pHead; } void showLink(pLinkNode pHead) { while(pHead) { printf("%d " , pHead->m_nKey); pHead = pHead->m_npNext; } printf("\n"); } pLinkNode reverseLink(pLinkNode pHead) { pLinkNode pCur , prHead ; pCur = pHead->m_npNext; if(!pHead) { return NULL; } prHead = pHead; while(pCur) { pHead->m_npNext = pCur->m_npNext; // A->B->C->D->NULL pHead = prHead = A pCur->m_npNext = prHead; //pCur->m_npNext变为新的头节点 prHead = pCur; pCur = pHead->m_npNext; //pCur始终是pHead->m_npNext } return prHead; } int main(int argc , char *argv[]) { pLinkNode pHead = create(); showLink(pHead); pHead = reverseLink(pHead); showLink(pHead); return 0; }
题目:输入一个链表的头结点,反转该链表,并返回反转后链表的头结点。
标签:数据结构
原文地址:http://blog.csdn.net/u011185633/article/details/44876583