链表反转-数据结构

分别设置三个指针。第一个指针保持结果,第二个指针指向当前的节点,第三个指针保存下一个节点

void reverseLinkList(LinkList *head)
{
	Linklist *p1,*p2,*p3;
	
	if(head == NULL)
		return 0;
		
	p1 = head;
	p2 = p1 -> next;
	
	while(p2)
	{
		p3= p2 -> next;
		p2 -> next = p1;
		p1 = p2;
		p2 = p3;
	}
	
	return;
}


下面就用c语言来具体的实现它:

#include
#include

/*链表结点*/
typedef struct node
{
	struct node *next;
	int data;
} *LinkList;

/*reverse function*/
static void reverse(LinkList *head_ref)
{
	LinkList prev = NULL;
	LinkList current = *head_ref;
	LinkList next;
	
	while(current)
	{
		next = current -> next;
		current -> next = prev;
		prev = current;
		current = next;
	}
	
	*head_ref = prev;
}

/*insert data*/
void insertData(LinkList *head_ref, int new_data)
{
	LinkList new_node = (LinkList)malloc(sizeof(LinkList));
	
	new_node -> data = new_data;
	new_node -> next = *head_ref;
	*head_ref = new_node;
}

/*printf the data list*/
void printList(LinkList head)
{
	LinkList temp = head;
	
	while(temp != NULL)
	{
		printf("%d ",temp -> data);
		temp = temp -> next;
	}
}

int main()
{
	LinkList head = NULL;
	
	insertData(&head,20);
	insertData(&head,4);
	insertData(&head,15);
	insertData(&head,85);
	insertData(&head,60);
	
	printList(head);
	reverse(&head);
	printf("\n Reverse Linked list\n");
	printList(head);

	return 0;
}


其中关于二级指针的学习在后续的文章中会持续的进行更新


你可能感兴趣的:(C/C++)