// 链表头指针结构
typedef struct header
{
int length; //存储链表结点个数
struct linklist *next;//指针域
} Header;
// 链表结点结构
typedef struct linknode
{
int data;//数据域
struct linknode* next;//指针域
} LinkNode;
//反转链表方式1 :迭代法初级版
void ReverseLink1(Header* header)
{
LinkNode* curr = header->next;
if(curr == NULL||curr->next == NULL)
{
return;
}
LinkNode* next1 = curr->next;
LinkNode* next2 = next1->next;
if(next2 == NULL)
{
next1->next = curr;
header->next = next1;
curr->next = NULL;
return;
}
while(next2 != NULL)
{
next1->next = curr;
curr = next1;
next1 = next2;
next2 = next2->next;
}
next1->next = curr;
header->next = next1;
}
//反转链表方式 :迭代法
void ReverseLink(Header* header)
{
LinkNode* curr = header->next;//当前指针
LinkNode* prev = NULL;//前驱指针
LinkNode* next = NULL;//后继指针
while(curr != NULL)//判断当前指针curr是否为空(为空表明遍历到链表尾部(不是尾结点))
{
next = curr->next;
curr->next = prev;
//整体后移
prev = curr;
curr = next;
}
header->next = prev;//最后别忘了将头结点指针指向prev,即反转后的第一个结点,注意不是curr
//因为curr结束循环后指向了NULL
}
????????空链表或单节点链表的判断也包含在其中,无需单独判断,比上面的第一个版本更简洁易懂。