链表翻转
链表相邻元素翻转,如a->b->c->d->e->f-g,翻转后变为:b->a->d->c->f->e->g
思路:常见的三指针方法
typedef struct LinkNode { int data; struct LinkNode* next; }LinkNode , *LinkList; LinkList inverseList(LinkList head) { if(head == NULL || head->next == NULL) return head; LinkList pre = NULL; LinkList curr = head; LinkList next = NULL; while(curr && curr->next) { if(pre) pre->next = curr->next; else head = curr->next; pre = curr; next = curr->next->next; curr->next->next = curr; curr->next = next; curr = next; } return head; }
//单链表定义: public class Link { public Link Next; public string Data; public Link(Link next, string data) { this.Next = next; this.Data = data; } } //反转算法实现一:(递归实现) public static Link ReverseLink3(Link head) { //if no elements or only one element exists if (head.Next == null || head.Next.Next == null) return head; head.Next = ReverseLink(head.Next); return head; } //接下来就是递归的核心算法ReverseLink了: static Link ReverseLink(Link head) { if (head.Next == null) return head; Link rHead = ReverseLink(head.Next); head.Next.Next = head; head.Next = null; return rHead; } //反转算法实现二:(非递归) //我们需要额外的两个变量来存储当前节点curr的下一个节点next、再下一个节点nextnext: public static Link ReverseLink1(Link head) { Link curr = head.Next; Link next = null; Link nextnext = null; //if no elements or only one element exists if (curr == null || curr.Next == null) { return head; } //if more than one element while (curr.Next != null) { next = curr.Next; //1 nextnext = next.Next; //2 next.Next = head.Next; //3 head.Next = next; //4 curr.Next = nextnext; //5 } return head; }