// test.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
struct ListNode
{
int m_nValue;
ListNode *m_pNext;
};
ListNode* CreateList(int val)
{
ListNode *pHead = new ListNode;
pHead->m_nValue = val;
pHead->m_pNext = NULL;
return pHead;
}
void InsertNode(ListNode **pHead, int val)
{
ListNode *pNode = new ListNode;
pNode->m_nValue = val;
pNode->m_pNext = NULL;
while ((*pHead)->m_pNext != NULL)
{
(*pHead) = (*pHead)->m_pNext;
}
(*pHead)->m_pNext = pNode;
(*pHead) = pNode;
}
void PrintList(ListNode *pHead)
{
while (pHead != NULL)
{
cout<<pHead->m_nValue<<" ";
pHead = pHead->m_pNext;
}
cout<<endl;
}
ListNode* Reverse(ListNode *pHead)
{
if (pHead == NULL || pHead->m_pNext == NULL)
{
return pHead;
}
ListNode *pPre = NULL;
ListNode *pCurrent = pHead;
ListNode *pPost = pHead->m_pNext;
while (pCurrent->m_pNext != NULL)
{
pCurrent->m_pNext = pPre;
pPre = pCurrent;
pCurrent = pPost;
pPost = pPost->m_pNext;
}
pCurrent->m_pNext = pPre;
return pCurrent;
}
ListNode* ReverseList(ListNode *pHead, int k)
{
if (pHead==NULL || pHead->m_pNext==NULL)
{
return pHead;
}
ListNode *pPre = NULL;
ListNode *pCurrent = pHead;
ListNode *pPost = pHead->m_pNext;
ListNode *pStart = NULL;
ListNode *pEnd = NULL;
int n = 0;
pEnd = pCurrent;
pEnd->m_pNext = NULL;
while (pPost != NULL)
{
++n;
if (n == (k+1))
{
pStart = pPre;
pEnd->m_pNext = ReverseList(pCurrent, k);
return pStart;
}
else
{
pCurrent->m_pNext = pPre;
pPre = pCurrent;
pCurrent = pPost;
pPost = pPost->m_pNext;
}
}
pCurrent->m_pNext = pPre;
pStart = pCurrent;
return pStart;
}
int main()
{
ListNode *pHead = NULL;
ListNode *head = NULL;
int n;
cout<<"输入链表中节点的个数 n:"<<endl;
cin>>n;
cout<<"请输入n个整数值:"<<endl;
for (int i=0; i<n; ++i)
{
int data;
cin>>data;
if (pHead == NULL)
{
pHead = CreateList(data);
head = pHead;
}
else
{
InsertNode(&pHead, data);
}
}
int k;
cout<<"请输入k:"<<endl;
cin>>k;
head = ReverseList(head, k);
PrintList(head);
system("pause");
return 0;
}
链表K个节点翻转
最新推荐文章于 2024-04-07 09:03:34 发布