链表必学算法(五):逆置法


/*单链表的操作:逆置法*/

/*
* SCs in different methods
* author: Whywait
*/

typedef struct node {
     
	Elemtype data;
	struct node* next;
} Lnode;

/*Method One*/

/*
* 三兄弟列队走
*/

Lnode* reverseSList(Linklist& L) {
     
	// this is a singly linked list with a head node
	// and I name the three brothers: one, two, three
	// but we need to face the special situation: there is less than 3 nodes in the list
	// so let's talk about it first

	Lnode* one, * two, * three;

	if (!L->next || !L->next->next) return L; // if there is one node or none, do nothing

	one = L->next;
	two = one->next;
	one->next = NULL;

	if (!two->next) {
      // if three are two nodes
		tow->next = one;
		L->next = two;
		return L;
	}

	three = two->next;
	while (three) {
      // if three are three or more than three nodes
		// three brothers go along the slist until the THREE brother is NULL
		two->next = one;
		one = two;
		two = three;
		three = three->next;
	}
	L->next = two;
	return L;
}

你可能感兴趣的:(算法,链表,算法,单链表,数据结构)